src/Services/Tools.php line 281

Open in your IDE?
  1. <?php
  2. // App/Services/Tools.php
  3. namespace App\Services;
  4. use Symfony\Component\HttpFoundation\JsonResponse;
  5. use Symfony\Component\HttpFoundation\Request;
  6. use Symfony\Component\HttpFoundation\Response;
  7. use Symfony\Component\Form\FormEvent;
  8. use Symfony\Component\Form\FormEvents;
  9. use Symfony\Component\Form\FormError;
  10. use Symfony\Component\DependencyInjection\ContainerInterface;
  11. use App\Entity\User;
  12. use Symfony\Component\HttpFoundation\Session\Session;
  13. use Symfony\Component\HttpFoundation\RequestStack;
  14. use Geocoder\Dumper\GeoJson;
  15. use Geocoder\Provider\Provider;
  16. use Geocoder\Query\GeocodeQuery;
  17. use Geocoder\Query\ReverseQuery;
  18. use \DateTime;
  19. //Load entity
  20. use App\Entity\PositionGps;
  21. use App\Entity\Hobit;
  22. use App\Entity\HobitDate;
  23. // Import the Twig Environment
  24. use Twig\Environment;
  25. class Tools
  26. {
  27. private $container;
  28. private $em;
  29. private $twig;
  30. private $mail_no_reply;
  31. private $acmeGeocoder;
  32. private $geoJsonDumper;
  33. public function __construct(ContainerInterface $container, \Doctrine\ORM\EntityManagerInterface $em, Environment $twig, Provider $acmeGeocoder, GeoJson $dumper) {
  34. $this->container = $container;
  35. $this->em = $em;
  36. $this->twig = $twig;
  37. $this->acmeGeocoder = $acmeGeocoder;
  38. $this->geoJsonDumper = $dumper;
  39. //$this->mail_no_reply = $container->getParameter('mail_no_reply');
  40. }
  41. /**
  42. * sub Phone number for international
  43. *
  44. * @param string $phone
  45. * @return string
  46. */
  47. public function subPhoneInternational($phone)
  48. {
  49. $fr = "+33";
  50. $phone_sub = substr($phone, 1);
  51. $phone_international = $fr.$phone_sub;
  52. return $phone_international;
  53. }
  54. /**
  55. * Send json rest successData
  56. *
  57. * @param string $code, $message, $data
  58. * @return json
  59. */
  60. public function successData($code, $message, $data, $type = Response::HTTP_OK)
  61. {
  62. $response = \FOS\RestBundle\View\View::create([
  63. 'success' => true,
  64. 'code'=> $code,
  65. 'message' => $message,
  66. 'data'=> $data],
  67. $type);
  68. return $response;
  69. }
  70. /**
  71. * Send json rest successBoolean
  72. *
  73. * @param string $code, $message
  74. * @return json
  75. */
  76. public function successBoolean($code, $message, $type = Response::HTTP_OK)
  77. {
  78. $response = \FOS\RestBundle\View\View::create([
  79. 'success' => true,
  80. 'code'=> $code,
  81. 'message' => $message],
  82. $type);
  83. return $response;
  84. }
  85. /**
  86. * Send json rest errorData
  87. *
  88. * @param string $code, $message, $data
  89. * @return json
  90. */
  91. public function errorData($code, $message, $data)
  92. {
  93. $response = \FOS\RestBundle\View\View::create([
  94. 'success' => false,
  95. 'code'=> $code,
  96. 'message' => $message,
  97. 'errors'=> $data],
  98. Response::HTTP_BAD_REQUEST);
  99. return $response;
  100. }
  101. /**
  102. * Send json rest errorBoolean
  103. *
  104. * @param string $code, $message
  105. * @return json
  106. */
  107. public function errorBoolean($code, $message, $type = Response::HTTP_BAD_REQUEST)
  108. {
  109. $response = \FOS\RestBundle\View\View::create([
  110. 'success' => false,
  111. 'code'=> $code,
  112. 'message' => $message],
  113. $type);
  114. return $response;
  115. }
  116. /**
  117. * Get form errors
  118. *
  119. * @param Array $form
  120. * @return Array
  121. */
  122. /*public function getFormErrors($form)
  123. {
  124. $errorCollection = array();
  125. foreach($form as $key => $child){
  126. $errorCollection[$key] = array();
  127. if(strstr($key, "Date") || strstr($key, "date") && ($key != "birthDateDay" && $key != "birthDateMonth" && $key != "birthDateYear")) {
  128. foreach($child as $keyDate => $childDate){
  129. if(count($childDate->getErrors()) > 0){
  130. $errorCollection[$key][$keyDate]["code"] = $childDate->getErrors()[0]->getCause()['payload']['code'];
  131. $errorCollection[$key][$keyDate]["message"] = $childDate->getErrors()[0]->getMessage();
  132. }
  133. }
  134. }
  135. else{
  136. if(count($child->getErrors()) > 0){
  137. $errorCollection[$key]['code'] = $child->getErrors()[0]->getCause()->getConstraint()->payload['code'];
  138. $errorCollection[$key]['message'] = $child->getErrors()[0]->getMessage();
  139. }
  140. }
  141. }
  142. return $errorCollection;
  143. }*/
  144. public function getFormErrors(\Symfony\Component\Form\Form $form) {
  145. $errors = array();
  146. foreach ($form->getErrors() as $key => $error) {
  147. if (!$form->isRoot()) {
  148. $cause = $error->getCause();
  149. if(array_key_exists("payload",$cause)){
  150. $payload = $cause["payload"];
  151. $code = $payload["code"];
  152. }
  153. else if ($cause instanceof \Symfony\Component\Validator\ConstraintViolation){
  154. $code = $cause->getConstraint()->payload['code'];
  155. }
  156. else{
  157. $code=null;
  158. }
  159. $errors['code'] = $code;
  160. //$errors['code'] = $error->getCause()['payload']['code'];
  161. $errors['message'] = $error->getMessage();
  162. //$errors[] = $error->getMessage();
  163. }
  164. }
  165. foreach ($form->all() as $child) {
  166. if (!$child->isValid()) {
  167. $childErrors = $this->container->get('app.tools')->getFormErrors($child);
  168. if(!empty($childErrors)){
  169. $errors[$child->getName()] =$childErrors;
  170. }
  171. }
  172. }
  173. return $errors;
  174. }
  175. /**
  176. * Set message encrypt
  177. *
  178. * @param string $message
  179. * @return String
  180. */
  181. public function encryptMessage($message)
  182. {
  183. $hash = "secretHashValue";
  184. $method = "AES-256-CBC";
  185. $iv_size = mcrypt_get_iv_size(MCRYPT_CAST_256, MCRYPT_MODE_CBC);
  186. $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
  187. $encrypted = openssl_encrypt($message, $method, $hash, 0, $iv);
  188. return base64_encode($iv . $encrypted);
  189. }
  190. /**
  191. * Get message encrypt
  192. *
  193. * @param string $message
  194. * @return String
  195. */
  196. public function decryptMessage($message)
  197. {
  198. $message = base64_decode($message);
  199. $hash = "secretHashValue";
  200. $method = "AES-256-CBC";
  201. $iv_size = mcrypt_get_iv_size(MCRYPT_CAST_256, MCRYPT_MODE_CBC);
  202. $iv = substr($message, 0, $iv_size);
  203. $decrypted = openssl_decrypt(substr($message, $iv_size), $method, $hash, 0, $iv);
  204. return $decrypted;
  205. }
  206. /**
  207. * Add notification
  208. *
  209. * @param string $message
  210. * @return Int idUser, String type, String message, String url
  211. */
  212. public function sendBasicEmail($user, $subject, $message, $emailDest = null)
  213. {
  214. //Load user
  215. $user = $this->em->getRepository(User::class)->find($user);
  216. if(!$user){
  217. return false;
  218. }
  219. if($emailDest==null){
  220. $emailDest = $user->getEmail();
  221. }
  222. //Create email
  223. $bodyEmail = $this->twig->render(
  224. 'Emails/basicEmail.html.twig',
  225. array('user' => $user, 'message' => $message)
  226. );
  227. /*
  228. //Load email
  229. $message = \Swift_Message::newInstance()
  230. ->setSubject($subject)
  231. ->setFrom($this->mail_no_reply)
  232. ->setTo($emailDest)
  233. ->setBody($bodyEmail,'text/html');
  234. //Send email
  235. $this->mailer->send($message);
  236. */
  237. return true;
  238. }
  239. public function dreamHobit($debug, $debugAndFlush, $limitWidthHobit, $limitTimeHobit, $limitForCreateHobit, $limitStable, $maxSum, $numberIntervalPrintedAndServer, $userCurrent = null, $dateEndForce = null, $dateStartForce = null)
  240. {
  241. //Load base
  242. $em = $this->container->get('doctrine.orm.entity_manager');
  243. $positionGpsListTemp = $em
  244. ->getRepository(PositionGps::class)
  245. ->findBy(array("sync" => 0, "user" => $userCurrent, "activityType" => "still"), array('datePrinted' => 'ASC', 'dateCreatedByServer' => 'ASC'), 50000);
  246. $positionGpsList = [];
  247. //Keep the good locations, no error gps
  248. foreach($positionGpsListTemp as $positionGpsTemp){
  249. if($positionGpsTemp->getAccuracy() < 150){
  250. $positionGpsList[] = $positionGpsTemp;
  251. }
  252. }
  253. $hobitsTemp = [];
  254. $keyCount = 1;
  255. //Keep the good activity, check, return good array
  256. $positionGpsList = $this->checkAccuracyPosition($positionGpsList, $limitTimeHobit, $userCurrent);
  257. foreach($positionGpsList as $positionGps){
  258. $lastPosition = false;
  259. $nextPositions = [];
  260. $nextPositionsKeep = [];
  261. $activtiesBetween = [];
  262. $activtiesBetweenNumber = 0;
  263. $activtiesBetweenI = 1;
  264. $activtiesBetweenType = [];
  265. $nextPositionKeepEnd = false;
  266. $nextStill = null;
  267. if(count($positionGpsList) == $keyCount){
  268. $lastPosition = true;
  269. }
  270. if($lastPosition){
  271. //Current activity
  272. }
  273. else{
  274. //determine the next position "still" for get the center positions
  275. $nextStill = $positionGpsList[$keyCount]; // KeyCount are +1
  276. //Get next positions
  277. $nextPositions = $em
  278. ->getRepository(PositionGps::class)
  279. ->findPositionNext(0, $userCurrent->getId(), 100, $positionGps->getId(), $nextStill->getId(), 150, 200000);
  280. //For all next positions between current position still and nex position still get
  281. foreach($nextPositions as $nextPosition){
  282. $distanceM = round($this->get_distance_m($positionGps, $nextPosition), 3);
  283. //If end still, get activity between end stil and next still position
  284. if($nextPositionKeepEnd == false){
  285. if($distanceM < $limitWidthHobit){
  286. $nextPositionsKeep[] = array("data" => $nextPosition, "distanceM" => $distanceM, "id" => $nextPosition->getId());
  287. }
  288. else{
  289. $nextPositionsKeep[] = array("data" => $nextPosition, "distanceM" => $distanceM, "id" => $nextPosition->getId());
  290. //End this hobit = break
  291. $nextPositionKeepEnd = true;
  292. }
  293. }
  294. else{
  295. //Get Activity (bike, foot, car, etc...) between this hobit and next hobit.
  296. if(!isset($activtiesBetweenType[$activtiesBetweenNumber][$nextPosition->getActivityType()])){
  297. $activtiesBetweenType[$nextPosition->getActivityType()] = 1;
  298. }
  299. else{
  300. $activtiesBetweenType[$nextPosition->getActivityType()]++;
  301. }
  302. // If activities has history (number > 1) and current activity same with last activity
  303. if($activtiesBetweenI > 1 && $nextPosition->getActivityType() != $activtiesBetween[$activtiesBetweenNumber]['hobits'][$activtiesBetweenI - 2]['data']->getActivityType()){
  304. //reset all variables
  305. $activtiesBetweenNumber++;
  306. $activtiesBetweenI = 0;
  307. $activtiesBetweenType = [];
  308. }
  309. //Array for type by hobit
  310. $activtiesBetween[$activtiesBetweenNumber]["activtiesBetweenType"] = $activtiesBetweenType;
  311. //Default number is 0 (for 1 activity)
  312. $activtiesBetween[$activtiesBetweenNumber]['hobits'][] =
  313. array(
  314. "data" => $nextPosition,
  315. "dataGps" => array("longitude" => $nextPosition->getLongitude(), "latitude" => $nextPosition->getLatitude()),
  316. "distanceM" => $distanceM,
  317. "id" => $nextPosition->getId(),
  318. "activityType" => $nextPosition->getActivityType(),
  319. )
  320. ;
  321. $activtiesBetweenI++;
  322. }
  323. //Debug and flush if this variable is : true
  324. if($debugAndFlush == true){
  325. $nextPosition->setSync(1);
  326. $em->persist($nextPosition);
  327. }
  328. }
  329. }
  330. $nextPositionsKeepLast = null;
  331. if(count($nextPositionsKeep) > 0){
  332. $nextPositionsKeepLast = $nextPositionsKeep[count($nextPositionsKeep) - 1]["data"];
  333. }
  334. if($nextPositionsKeepLast){
  335. $endDateTime = $nextPositionsKeepLast->getDatePrinted();
  336. }
  337. else{
  338. if($lastPosition){
  339. $endDateTime = new \DateTime();
  340. }
  341. else{
  342. $endDateTime = $nextStill->getDatePrinted();
  343. }
  344. }
  345. // REMOVE SMALL HOBIT (> $limitTimeHobit seconds)
  346. if(($endDateTime->format("YmdHis") - $positionGps->getDatePrinted()->format("YmdHis")) > $limitTimeHobit){
  347. $hobitsTemp[] = array(
  348. "startDateTime" => $positionGps->getDatePrinted(),
  349. "endDateTime" => $endDateTime,
  350. "startDateTimeServer" => $positionGps->getDateCreatedByServer(),
  351. "id" => $positionGps->getId(),
  352. "activityType" => $positionGps->getActivityType(),
  353. "data" => $positionGps,
  354. "nextStillId" => ($nextStill) ? $nextStill->getId() : null,
  355. "positions" => $nextPositionsKeep,
  356. );
  357. }
  358. //For hobit activity between
  359. if(count($activtiesBetween) > 0){
  360. foreach($activtiesBetween as $key => $activityBetween){
  361. if(count($activityBetween['hobits']) >= 10){
  362. $activtyBetweenFirst = $activityBetween['hobits'][0]['data'];
  363. $activtyBetweenLast = $activityBetween['hobits'][count($activityBetween['hobits']) - 1]['data'];
  364. $maxValue = max($activityBetween['activtiesBetweenType']);
  365. $activityType = array_search($maxValue, $activityBetween['activtiesBetweenType']);
  366. $hobitsTemp[] = array(
  367. "startDateTime" => $activtyBetweenFirst->getDatePrinted(),
  368. "endDateTime" => $activtyBetweenLast->getDatePrinted(),
  369. "startDateTimeServer" => $activtyBetweenFirst->getDateCreatedByServer(),
  370. "activityType" => $activityType,
  371. "firstPosition" => $activityBetween['hobits'][0],
  372. "lastPosition" => $activityBetween['hobits'][count($activityBetween['hobits']) - 1],
  373. "positions" => $activityBetween['hobits'],
  374. );
  375. }
  376. }
  377. }
  378. if($debugAndFlush == true){
  379. //Sync all positions, but no current position
  380. if(!$lastPosition){
  381. $positionGps->setSync(1);
  382. $em->persist($positionGps);
  383. }
  384. }
  385. $em->flush();
  386. $keyCount++;
  387. }
  388. return $hobitsTemp;
  389. }
  390. //Check if positon less 100, then correct or no (for still)
  391. public function checkAccuracyPosition($positionsGps, $limitTimeHobit, $userCurrent){
  392. $positionsGpsGood = [];
  393. $i = 1;
  394. foreach($positionsGps as $positionGps){
  395. if(!$positionGps || ($positionGps && !$positionGps->getId()) || !$userCurrent){
  396. continue;
  397. }
  398. if($positionGps->getActivityConfidence() == 100 && !$positionGps->isIsMoving()){
  399. //It's perfect activity
  400. $positionsGpsGood[] = $positionGps;
  401. }
  402. else{
  403. if(count($positionsGps) == $i){
  404. //For last activity "still"
  405. $positionsGpsGood[] = $positionGps;
  406. }
  407. else{
  408. /*
  409. if($positionGps->getFloor() == "-1"){
  410. $positionsGpsGood[] = $positionGps;
  411. continue;
  412. }
  413. */
  414. //Remove speed fail (-1) // See for motionChange ?
  415. if($positionGps->getSpeed() != "-1"){
  416. //If during postion bigger than $limitTimeHobit (in second)
  417. $nextOnePosition = $this->em
  418. ->getRepository(PositionGps::class)
  419. ->findOnePositionNext(0, $userCurrent->getId(), $positionGps->getId(), 150);
  420. if(($nextOnePosition[0]->getDatePrinted()->getTimestamp() - $positionGps->getDatePrinted()->getTimestamp()) > 600){
  421. $positionsGpsGood[] = $positionGps;
  422. }
  423. }
  424. }
  425. }
  426. $i++;
  427. }
  428. return $positionsGpsGood;
  429. }
  430. //LAST FUNCTION, NOT USE
  431. public function dreamHobitLAST($debug, $debugAndFlush, $limitWidthHobit, $limitTimeHobit, $limitForCreateHobit, $limitStable, $maxSum, $numberIntervalPrintedAndServer, $userCurrent = null, $dateEndForce = null, $dateStartForce = null)
  432. {
  433. //Load base
  434. $em = $this->container->get('doctrine.orm.entity_manager');
  435. $tabHobit = [];
  436. $tabHobitTemp = [];
  437. $t = 0;
  438. $a = 0;
  439. $i = 0;
  440. $hour = null;
  441. $hourLast = null;
  442. $isNewHobit = true;
  443. $positionGpsList = [];
  444. $testDump = false;
  445. //remove fail date
  446. $datetimeFail = new DateTime();
  447. $newDateFail = $datetimeFail->createFromFormat('Y-m-d H:i:s', '1970-01-01 01:00:00');
  448. $positionGpsListFails = $this->container->get('doctrine.orm.entity_manager')
  449. ->getRepository(PositionGps::class)
  450. ->findBy(array("datePrinted" => $newDateFail, "user" => $userCurrent, "activityType" => "still"));
  451. foreach ($positionGpsListFails as $fail) {
  452. $fail->setSync(1);
  453. $em->persist($fail);
  454. }
  455. $em->flush();
  456. //Get all positions no sync
  457. if($dateEndForce && $dateStartForce){
  458. $positionGpsListTemp = $this->container->get('doctrine.orm.entity_manager')
  459. ->getRepository(PositionGps::class)
  460. ->findBy(array("sync" => 0, "user" => $userCurrent), array('datePrinted' => 'ASC', 'dateCreatedByServer' => 'ASC'), 50000);
  461. foreach($positionGpsListTemp as $pos){
  462. if($pos->getDateCreatedByServer()->format("YmdHis") < $dateEndForce && $pos->getDateCreatedByServer()->format("YmdHis") > $dateStartForce){
  463. $positionGpsList[] = $pos;
  464. }
  465. }
  466. }
  467. else if($dateEndForce){
  468. $positionGpsListTemp = $this->container->get('doctrine.orm.entity_manager')
  469. ->getRepository(PositionGps::class)
  470. ->findBy(array("sync" => 0, "user" => $userCurrent), array('datePrinted' => 'ASC', 'dateCreatedByServer' => 'ASC'), 50000);
  471. foreach($positionGpsListTemp as $pos){
  472. if($pos->getDateCreatedByServer()->format("YmdHis") < $dateEndForce){
  473. $positionGpsList[] = $pos;
  474. }
  475. }
  476. }
  477. else if($dateStartForce){
  478. $positionGpsListTemp = $this->container->get('doctrine.orm.entity_manager')
  479. ->getRepository(PositionGps::class)
  480. ->findBy(array("sync" => 0, "user" => $userCurrent), array('datePrinted' => 'ASC', 'dateCreatedByServer' => 'ASC'), 50000);
  481. foreach($positionGpsListTemp as $pos){
  482. if($pos->getDateCreatedByServer()->format("YmdHis") > $dateStartForce){
  483. $positionGpsList[] = $pos;
  484. }
  485. }
  486. }
  487. else{
  488. $positionGpsList = $this->container->get('doctrine.orm.entity_manager')
  489. ->getRepository(PositionGps::class)
  490. ->findBy(array("sync" => 0, "user" => $userCurrent), array('datePrinted' => 'ASC', 'dateCreatedByServer' => 'ASC'), 50000);
  491. }
  492. if($testDump){
  493. var_dump("1 : ".count($positionGpsList));
  494. }
  495. if($positionGpsList){
  496. $numberPosition = count($positionGpsList);
  497. foreach ($positionGpsList as $keyPositionGps => $positionGps) {
  498. $i++;
  499. if(intval($positionGps->getAccuracy()) < 100){
  500. $hour = $positionGps->getDatePrinted()->format("is");
  501. //if($hourLast != $hour || $hourLast == null){
  502. $hourLast = $hour;
  503. if($positionGps->getSpeed() < 10){
  504. //if($positionGps->getSpeed() == 0 || $positionGps->getSpeed() == -1){
  505. $backgroundDuring = false;
  506. if(($positionGps->getDateCreatedByServer()->format("YmdHis") - $positionGps->getDatePrinted()->format("YmdHis")) > $numberIntervalPrintedAndServer){
  507. $backgroundDuring = true;
  508. }
  509. if(count($tabHobit) == 0){
  510. $tabHobit[$a]['data'] = $positionGps;
  511. $tabHobit[$a]['move'] = false;
  512. $tabHobit[$a]['startDateTime'] = $positionGps->getDatePrinted();
  513. $tabHobit[$a]['startDateTimeServer'] = $positionGps->getDateCreatedByServerFormat();
  514. $tabHobit[$a]['number'] = 1;
  515. $tabHobit[$a]['group'][] = $positionGps;
  516. if($backgroundDuring){
  517. $tabHobit[$a]['backgroundDuring'] = true;
  518. }
  519. else{
  520. $tabHobit[$a]['backgroundDuring'] = false;
  521. }
  522. }
  523. else{
  524. //Number between last geo and new geo
  525. $numberRayon = round($this->get_distance_m($tabHobit[$a]['data'], $positionGps) / 1000, 3);
  526. $asExistHobit = false;
  527. if($numberRayon < $limitWidthHobit){
  528. $asExistHobit = true;
  529. }
  530. //For background data
  531. if(!$backgroundDuring){
  532. for($o = 1; $o <= $limitForCreateHobit; $o++){
  533. if($asExistHobit == false){
  534. if($numberPosition != ($i + $o) and $numberPosition > ($i + $o)){
  535. $numberRayon = round($this->get_distance_m($tabHobit[$a]['data'], $positionGpsList[$keyPositionGps + $o]) / 1000, 3);
  536. if($numberRayon < $limitWidthHobit){
  537. $asExistHobit = true;
  538. }
  539. }
  540. }
  541. }
  542. }
  543. if($asExistHobit == true){
  544. $tabHobit[$a]['number'] = $tabHobit[$a]['number'] + 1;
  545. //echo "old - ".$positionGps->getDatePrinted()->format("d-m-Y H-i");
  546. //echo "</br>";
  547. //echo $numberRayon;
  548. //echo "<br/>";
  549. //It's sum on XX address number for a good data :)
  550. if($tabHobit[$a]['number'] > 5){
  551. if(isset($tabHobit[$a]['group'])){
  552. if(count($tabHobit[$a]['group']) < $maxSum){
  553. $tabHobit[$a]['group'][] = $positionGps;
  554. }
  555. }
  556. else{
  557. $tabHobit[$a]['group'][] = $positionGps;
  558. }
  559. }
  560. $t = 0;
  561. }
  562. else{
  563. if($isNewHobit == true){
  564. if($keyPositionGps > 2){
  565. //Review
  566. if($backgroundDuring){
  567. if(isset($tabHobit[$a]['group'])){
  568. /*
  569. $tabHobitTemp['last']['endDateTime'] = $tabHobit[$a]['group'][(count($tabHobit[$a]['group']) - 1)]->getDateCreatedByServer();
  570. $tabHobitTemp['last']['endDateTimeServer'] = $tabHobit[$a]['group'][(count($tabHobit[$a]['group']) - 1)]->getDateCreatedByServerFormat();
  571. */
  572. $tabHobitTemp['last']['endDateTime'] = $positionGpsList[($i -2)]->getDateCreatedByServer();
  573. $tabHobitTemp['last']['endDateTimeServer'] = $positionGps->getDateCreatedByServerFormat();
  574. }
  575. else{
  576. $tabHobitTemp['last']['endDateTime'] = $positionGpsList[($i -2)]->getDateCreatedByServer();
  577. $tabHobitTemp['last']['endDateTimeServer'] = $positionGps->getDateCreatedByServerFormat();
  578. }
  579. }
  580. else{
  581. if(isset($tabHobit[$a]['group'])){
  582. /*
  583. $tabHobitTemp['last']['endDateTime'] = $tabHobit[$a]['group'][(count($tabHobit[$a]['group']) - 1)]->getDatePrinted();
  584. $tabHobitTemp['last']['endDateTimeServer'] = $tabHobit[$a]['group'][(count($tabHobit[$a]['group']) - 1)]->getDateCreatedByServerFormat();
  585. */
  586. $tabHobitTemp['last']['endDateTime'] = $positionGpsList[($i -2)]->getDatePrinted();
  587. $tabHobitTemp['last']['endDateTimeServer'] = $positionGps->getDateCreatedByServerFormat();
  588. }
  589. else{
  590. $tabHobitTemp['last']['endDateTime'] = $positionGpsList[($i -2)]->getDatePrinted();
  591. $tabHobitTemp['last']['endDateTimeServer'] = $positionGps->getDateCreatedByServerFormat();
  592. }
  593. }
  594. $tabHobitTemp['last']['id'] = $a;
  595. $isNewHobit = false;
  596. }
  597. }
  598. //Let's go for a new hobit
  599. $tabHobitTemp['new'][$t]['data'] = $positionGps;
  600. $tabHobitTemp['new'][$t]['startDateTime'] = $positionGps->getDatePrinted();
  601. if($backgroundDuring){
  602. $tabHobitTemp['new'][$t]['startDateTimeServer'] = $positionGps->getDatePrintedFormat();
  603. }
  604. else{
  605. $tabHobitTemp['new'][$t]['startDateTimeServer'] = $positionGps->getDateCreatedByServerFormat();
  606. }
  607. $tabHobitTemp['new'][$t]['number'] = 1;
  608. $numberRayon = round($this->get_distance_m($tabHobitTemp['new'][0]['data'], $positionGps) / 1000, 3);
  609. //default : 0.020
  610. if($numberRayon < 0.010){
  611. //echo "if : ".$numberRayon;
  612. //echo "<br/>";
  613. $t++;
  614. }
  615. else{
  616. $t = 0;
  617. //echo "else : ".$numberRayon;
  618. //var_dump($positionGps);
  619. //echo "<br/>";
  620. //die;
  621. //echo "current - ".$positionGps->getDatePrinted()->format("d-m-Y H-i");
  622. //echo "</br>";
  623. }
  624. //New hobit TEMP
  625. if($t > $limitStable || $backgroundDuring){
  626. if(isset($tabHobitTemp['last'])){
  627. // Set the end date for the last hobit
  628. $tabHobit[$tabHobitTemp['last']['id']]['endDateTime'] = $tabHobitTemp['last']['endDateTime'];
  629. $tabHobit[$tabHobitTemp['last']['id']]['endDateTimeServer'] = $tabHobitTemp['last']['endDateTimeServer'];
  630. }
  631. $isNewHobit = true;
  632. //New hobit
  633. $a++;
  634. $tabHobit[$a]['number'] = 0;
  635. if($backgroundDuring){
  636. $tabHobit[$a]['backgroundDuring'] = true;
  637. }
  638. else{
  639. $tabHobit[$a]['backgroundDuring'] = false;
  640. }
  641. foreach ($tabHobitTemp['new'] as $hobitTemp) {
  642. //echo "new - ".$hobitTemp['startDateTime']->format("d-m-Y H-i");
  643. //echo "</br>";
  644. //Let's go for a new hobit
  645. $tabHobit[$a]['data'] = $hobitTemp['data'];
  646. $tabHobit[$a]['startDateTime'] = $tabHobitTemp['new'][0]['startDateTime'];
  647. $tabHobit[$a]['startDateTimeServer'] = $tabHobitTemp['new'][0]['startDateTimeServer'];
  648. $tabHobit[$a]['number'] = $limitStable + $tabHobit[$a]['number'];
  649. }
  650. }
  651. }
  652. }
  653. }
  654. else{
  655. //For a travel
  656. }
  657. //}
  658. }
  659. else{
  660. $em->persist($positionGps);
  661. }
  662. if(count($tabHobit) != 0){
  663. if($numberPosition == $i){
  664. //For the last line
  665. $tabHobit[$a]['endDateTime'] = $positionGps->getDatePrinted();
  666. $tabHobit[$a]['endDateTimeServer'] = $positionGps->getDateCreatedByServerFormat();
  667. }
  668. }
  669. if($debugAndFlush == true || $debug == false){
  670. $em->remove($positionGps);
  671. }
  672. }
  673. $em->flush();
  674. //Delete logs
  675. //$em->flush();
  676. //Find the actualy hobits
  677. /* $actualyHobits = $this->get('doctrine.orm.entity_manager')
  678. ->getRepository('HobitBundle:Hobit')
  679. ->findBy(Array("status" => Hobit::NOW)); */
  680. /*
  681. foreach ($tabHobit as $hobit) {
  682. $start = strtotime($hobit['startDateTime']->format("Y-m-d H:i:s"));
  683. $end = strtotime($hobit['endDateTime']->format("Y-m-d H:i:s"));
  684. $dateBetween = $end - $start;
  685. $history = false;
  686. //Just for debug with navigator html
  687. if($dateBetween > $limitTimeHobit){
  688. if($hobit['number'] >= $limitForCreateHobit){
  689. //Set a new hobit
  690. $newHobit = new Hobit();
  691. foreach ($actualyHobits as $actualyHobit) {
  692. if(round($this->get_distance_m($actualyHobit, $hobit['data']) / 1000, 3) < $limitWidthHobit){
  693. $history = true;
  694. }
  695. }
  696. if($history == true){
  697. //Set type hystory
  698. $newHobit->setStatus(Hobit::HISTORY);
  699. }
  700. else{
  701. //Set type now
  702. $newHobit->setStatus(Hobit::NOW);
  703. }
  704. $curl = new \Ivory\HttpAdapter\CurlHttpAdapter();
  705. $geocoder = new \Geocoder\Provider\GoogleMaps($curl);
  706. $adresse = $geocoder->reverse($hobit['data']->getLatitude(), $hobit['data']->getLongitude());
  707. $fullAddress = $adresse->get(0)->getStreetNumber()." ".$adresse->get(0)->getStreetName().' '.$adresse->get(0)->getLocality().' '.$adresse->get(0)->getPostalCode().' '.$adresse->get(0)->getCountry()->getName();
  708. //Set property
  709. $newHobit->setName("Habitude");
  710. $newHobit->setAddress($fullAddress);
  711. $newHobit->setLatitude($hobit['data']->getLatitude());
  712. $newHobit->setLongitude($hobit['data']->getLongitude());
  713. $newHobit->setType(Hobit::LEISURE);
  714. $newHobit->setDateStartHobit($hobit['startDateTime']);
  715. $newHobit->setDateEndHobit($hobit['endDateTime']);
  716. $newHobit->setNumberRequest($hobit['number']);
  717. $em->persist($newHobit);
  718. }
  719. }
  720. }
  721. if($debugAndFlush == true || $debug == false){
  722. //Add hobit
  723. $em->flush();
  724. }
  725. */
  726. }
  727. //var_dump($tabHobit);
  728. //die;
  729. //remove small hobit
  730. /*
  731. $cleanHobit = [];
  732. foreach ($tabHobit as $hobit) {
  733. if(($hobit['endDateTime']->format("YmdHis") - $hobit['startDateTime']->format("YmdHis")) > $limitTimeHobit){
  734. $cleanHobit[] = $hobit;
  735. }
  736. }
  737. */
  738. //Just for debug
  739. if($debug == true){
  740. //return $cleanHobit;
  741. return $tabHobit;
  742. }
  743. else{
  744. return true;
  745. }
  746. }
  747. public function createHobit($hobits, $limitWidthHobit, $limitTimeHobit, $limitForCreateHobit, $maxSum, $userCurrent){
  748. /* TEST */
  749. /*
  750. $adresse = $this->container
  751. ->get('bazinga_geocoder.provider.acme')
  752. ->reverseQuery(ReverseQuery::fromCoordinates("47.798791858866", "3.5298856962337"));
  753. var_dump($adresse->get(0)->getId());
  754. die;
  755. */
  756. /* TEST */
  757. //Load base
  758. $em = $this->container->get('doctrine.orm.entity_manager');
  759. set_time_limit(0);
  760. ini_set('max_execution_time', 300);
  761. $limitWidthHobit = 0.030;
  762. $numberHobitCurrent = 1;
  763. $hobitPush = false;
  764. $actualyHobits = $this->container->get('doctrine.orm.entity_manager')
  765. ->getRepository(Hobit::class)
  766. ->findBy(Array("status" => "NOW", "user" => $userCurrent));
  767. $hobitsClean = $hobits;
  768. /*
  769. //remove no complete hobit
  770. foreach ($hobits as $hobit) {
  771. if($hobit['number'] >= $limitForCreateHobit || $hobit['backgroundDuring']){
  772. if(isset($hobit['endDateTime'])){
  773. $start = strtotime($hobit['startDateTime']->format("Y-m-d H:i:s"));
  774. $end = strtotime($hobit['endDateTime']->format("Y-m-d H:i:s"));
  775. $dateBetween = $end - $start;
  776. if($dateBetween > $limitTimeHobit){
  777. $hobitsClean[] = $hobit;
  778. }
  779. }
  780. }
  781. }
  782. */
  783. $numberHobit = count($hobitsClean);
  784. foreach($hobitsClean as $keyHobit => $hobit) {
  785. $now = false;
  786. //if($numberHobit > 0 && $numberHobit == $numberHobitCurrent && count($actualyHobits) > 0){
  787. // $now = true;
  788. //}
  789. if($numberHobit > 0 && $keyHobit == 0 && count($actualyHobits) > 0){
  790. if(round($this->get_distance_m($actualyHobits[0], $hobit['data']) / 1000, 3) < $limitWidthHobit){
  791. $now = true;
  792. }
  793. }
  794. $historyHobits = $this->container->get('doctrine.orm.entity_manager')
  795. ->getRepository(Hobit::class)
  796. ->findBy(array("user" => $userCurrent));
  797. $history = false;
  798. if($hobit['activityType'] == "still"){
  799. $hobitTemp = [];
  800. if($now == false){
  801. foreach($historyHobits as $historyHobit) {
  802. if(round($this->get_distance_m($historyHobit, $hobit['data']) / 1000, 3) < $limitWidthHobit){
  803. $history = true;
  804. $hobitTemp = $historyHobit;
  805. $hobitDateLast = $this->container->get('doctrine.orm.entity_manager')
  806. ->getRepository(HobitDate::class)
  807. ->findOneBy(Array("hobit" => $historyHobit, "status" => "LAST"));
  808. if($hobitDateLast){
  809. $hobitDateLast->setStatus(HobitDate::HISTORY);
  810. // FOR TEST TEMP
  811. $em->persist($hobitDateLast);
  812. $em->flush();
  813. }
  814. }
  815. }
  816. }
  817. //Calc SUM IN XX ADDRESS
  818. $totalLat = 0;
  819. $totalLng = 0;
  820. if($hobit['activityType'] == "still"){
  821. $totalLat = $hobit['data']->getLatitude();
  822. $totalLng = $hobit['data']->getLongitude();
  823. }
  824. $hobits[$keyHobit]['sumAddress']['latitude'] = $totalLat;
  825. $hobits[$keyHobit]['sumAddress']['longitude'] = $totalLng;
  826. if($history == true || $now == true){
  827. //Set a new date hobit
  828. if($now == false){
  829. $newHobitDate = new HobitDate();
  830. $newHobitDate->setDateStartHobit($hobit['startDateTime']);
  831. // $newHobitDate->setNumberRequest($hobit['number']);
  832. $newHobitDate->setHobit($hobitTemp);
  833. }
  834. else{
  835. $newHobitDate = $actualyHobits[0];
  836. //$newHobitDate->setNumberRequest($hobit['number'] + $actualyHobits[0]->getNumberRequest());
  837. $newHobitDate->setHobit($actualyHobits[0]->getHobit());
  838. }
  839. $newHobitDate->setLatitude($totalLat);
  840. $newHobitDate->setLongitude($totalLng);
  841. $newHobitDate->setDateEndHobit($hobit['endDateTime']);
  842. if($numberHobitCurrent == $numberHobit){
  843. if($now == false){
  844. if(count($actualyHobits) > 0){
  845. $actualyHobits[0]->setStatus("LAST");
  846. $em->persist($actualyHobits[0]);
  847. }
  848. }
  849. $newHobitDate->setStatus("NOW");
  850. }
  851. else{
  852. $newHobitDate->setStatus("LAST");
  853. }
  854. // FOR TEST TEMP
  855. $em->persist($newHobitDate);
  856. $em->flush();
  857. }
  858. else{
  859. //Set a new hobit
  860. $newHobit = new Hobit();
  861. //Set type now
  862. //$newHobit->setStatus("LAST");
  863. $newHobit->setParent(NULL);
  864. $adresse = $this->acmeGeocoder
  865. ->reverseQuery(ReverseQuery::fromCoordinates($totalLat, $totalLng));
  866. //var_dump($adresse);
  867. //die;
  868. $goodAddress = "";
  869. $zoneAddress = [];
  870. $locationType = "";
  871. $idPlace = "";
  872. $addressTempTab = [];
  873. if($adresse->count() > 1){
  874. foreach ($adresse->all() as $keyAddress => $oneAddress) {
  875. $addressTemp = $oneAddress->getStreetNumber()." ".$oneAddress->getStreetName().' '.$oneAddress->getLocality().' '.$oneAddress->getPostalCode().' '.$oneAddress->getCountry()->getName();
  876. if($keyAddress < 3){
  877. if($key = array_search($addressTemp, $addressTempTab, true)){
  878. if($addressTempTab[$key] == $addressTemp){
  879. $goodAddress = $addressTemp;
  880. $locationType = $oneAddress->getLocationType();
  881. $idPlace = $oneAddress->getId();
  882. $zoneAddress['streetNumber'] = $oneAddress->getStreetNumber();
  883. $zoneAddress['streetName'] = $oneAddress->getStreetName();
  884. $zoneAddress['locality'] = $oneAddress->getLocality();
  885. $zoneAddress['postalCode'] = $oneAddress->getPostalCode();
  886. $zoneAddress['country'] = $oneAddress->getCountry()->getName();
  887. }
  888. }
  889. }
  890. $addressTempTab[] = $addressTemp;
  891. }
  892. if($goodAddress == ""){
  893. $goodAddress = $adresse->get(0)->getStreetNumber()." ".$adresse->get(0)->getStreetName().' '.$adresse->get(0)->getLocality().' '.$adresse->get(0)->getPostalCode().' '.$adresse->get(0)->getCountry()->getName();
  894. $locationType = $adresse->get(0)->getLocationType();
  895. $idPlace = $adresse->get(0)->getId();
  896. $zoneAddress['streetNumber'] = $adresse->get(0)->getStreetNumber();
  897. $zoneAddress['streetName'] = $adresse->get(0)->getStreetName();
  898. $zoneAddress['locality'] = $adresse->get(0)->getLocality();
  899. $zoneAddress['postalCode'] = $adresse->get(0)->getPostalCode();
  900. $zoneAddress['country'] = $adresse->get(0)->getCountry()->getName();
  901. }
  902. }
  903. else{
  904. $goodAddress = $adresse->get(0)->getStreetNumber()." ".$adresse->get(0)->getStreetName().' '.$adresse->get(0)->getLocality().' '.$adresse->get(0)->getPostalCode().' '.$adresse->get(0)->getCountry()->getName();
  905. $locationType = $adresse->get(0)->getLocationType();
  906. $idPlace = $adresse->get(0)->getId();
  907. $zoneAddress['streetNumber'] = $adresse->get(0)->getStreetNumber();
  908. $zoneAddress['streetName'] = $adresse->get(0)->getStreetName();
  909. $zoneAddress['locality'] = $adresse->get(0)->getLocality();
  910. $zoneAddress['postalCode'] = $adresse->get(0)->getPostalCode();
  911. $zoneAddress['country'] = $adresse->get(0)->getCountry()->getName();
  912. }
  913. //Set property
  914. $newHobit->setName("Habitude");
  915. $newHobit->setAddress($goodAddress);
  916. $newHobit->setLatitude($totalLat);
  917. $newHobit->setLongitude($totalLng);
  918. $newHobit->setLocationType($locationType);
  919. $newHobit->setIdPlace($idPlace);
  920. $newHobit->setType($hobit['activityType']);
  921. $newHobit->setStatus("LAST");
  922. $newHobit->setUser($userCurrent);
  923. $newHobit->setNumberStreet( $zoneAddress['streetNumber'] );
  924. $newHobit->setStreet($zoneAddress['streetName']);
  925. $newHobit->setCity($zoneAddress['locality']);
  926. $newHobit->setCountry($zoneAddress['country']);
  927. $newHobit->setPostalCode($zoneAddress['postalCode']);
  928. //REMOVE FOR A VERSION 2, AFTER TEST
  929. $newHobit->setDateStartHobit($hobit['startDateTime']);
  930. $newHobit->setDateEndHobit($hobit['endDateTime']);
  931. $newHobit->setNumberRequest(count($hobit['positions']));
  932. //REMOVE FOR A VERSION 2, AFTER TEST
  933. $em->persist($newHobit);
  934. //Set a new date hobit
  935. $newHobitDate = new HobitDate();
  936. $newHobitDate->setLatitude($totalLat);
  937. $newHobitDate->setLongitude($totalLng);
  938. $newHobitDate->setDateStartHobit($hobit['startDateTime']);
  939. $newHobitDate->setDateEndHobit($hobit['endDateTime']);
  940. $newHobitDate->setNumberRequest(count($hobit['positions']));
  941. $newHobitDate->setHobit($newHobit);
  942. if($numberHobitCurrent == $numberHobit){
  943. if($now == false){
  944. if(count($actualyHobits) > 0){
  945. $actualyHobits[0]->setStatus("LAST");
  946. $em->persist($actualyHobits[0]);
  947. }
  948. }
  949. $newHobitDate->setStatus("NOW");
  950. }
  951. else{
  952. $newHobitDate->setStatus("LAST");
  953. }
  954. //FOR TEST TEMP
  955. $em->persist($newHobitDate);
  956. $em->flush();
  957. }
  958. $numberHobitCurrent++;
  959. /*
  960. if($numberHobit > 0){
  961. //Enable the position sync
  962. //$startDate = $hobits[0]['startDateTime'];
  963. //$endDate = $hobits[$numberHobit - 2]['endDateTime'];
  964. $startDate = $hobit['startDateTime'];
  965. $endDate = $hobit['endDateTime'];
  966. $hobitPush = true;
  967. // FOR TEST TEMP
  968. $positionsForSync = $this->container->get('doctrine.orm.entity_manager')
  969. ->getRepository(PositionGps::class)
  970. ->findPositionByTwoDate($startDate, $endDate, $userCurrent);
  971. //All positions no sync this is a "transition", transport... :) It's easy.
  972. }
  973. */
  974. $body = "Hobit create <br/><br/>";
  975. }
  976. else{
  977. $body = "Hobit NO create (limit) <br/><br/>";
  978. }
  979. $body.= "Date start : ".$hobit['startDateTime']->format("d-m-Y H:i");
  980. $body.= "<br/>Date end : ".$hobit['endDateTime']->format("d-m-Y H:i");
  981. /*
  982. $message = (new \Swift_Message('Life - dump hobit'))
  983. ->setFrom('noreply@69dev.io')
  984. ->setTo('grabettetristan@gmail.com')
  985. ->setBody(
  986. $body,
  987. 'text/html'
  988. )
  989. ;
  990. */
  991. //$this->container->get('mailer')->send($message);
  992. }
  993. //For cut the "transition"
  994. /*
  995. if($numberHobit > 0 && $hobitPush == true){
  996. $startDate = $hobits[0]['startDateTime'];
  997. $endDate = $hobitsClean[count($hobitsClean) - 1]['endDateTime'];
  998. // FOR TEST TEMP
  999. $positionsTransitionSync = $this->container->get('doctrine.orm.entity_manager')
  1000. ->getRepository(PositionGps::class)
  1001. ->findPositionByTwoDate($startDate, $endDate, $userCurrent);
  1002. }
  1003. */
  1004. return $hobitsClean;
  1005. }
  1006. function get_distance_m($lastHobit, $newHobit) {
  1007. $lat1 = $lastHobit->getLatitude();
  1008. $lng1 = $lastHobit->getLongitude();
  1009. $lat2 = $newHobit->getLatitude();
  1010. $lng2 = $newHobit->getLongitude();
  1011. $earth_radius = 6378137;
  1012. $rlo1 = deg2rad($lng1);
  1013. $rla1 = deg2rad($lat1);
  1014. $rlo2 = deg2rad($lng2);
  1015. $rla2 = deg2rad($lat2);
  1016. $dlo = ($rlo2 - $rlo1) / 2;
  1017. $dla = ($rla2 - $rla1) / 2;
  1018. $a = (sin($dla) * sin($dla)) + cos($rla1) * cos($rla2) * (sin($dlo) * sin($dlo));
  1019. $d = 2 * atan2(sqrt($a), sqrt(1 - $a));
  1020. return ($earth_radius * $d);
  1021. }
  1022. }