Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

607 lines
26KB

  1. <?php
  2. namespace Lc\ShopBundle\Services;
  3. use Cocur\Slugify\Slugify;
  4. use Doctrine\ORM\EntityManagerInterface;
  5. use EasyCorp\Bundle\EasyAdminBundle\Configuration\ConfigManager;
  6. use Geocoder\Model\Coordinates;
  7. use Geocoder\Provider\Addok\Addok;
  8. use Geocoder\Provider\GoogleMaps\GoogleMaps;
  9. use Geocoder\Provider\Nominatim\Nominatim;
  10. use Geocoder\Query\GeocodeQuery;
  11. use Geocoder\Query\ReverseQuery;
  12. use Lc\ShopBundle\Context\ImageInterface;
  13. use Lc\ShopBundle\Context\MerchantUtilsInterface;
  14. use Lc\ShopBundle\Context\PageInterface;
  15. use Lc\ShopBundle\Context\PointSaleInterface;
  16. use Lc\ShopBundle\Context\ProductFamilyInterface;
  17. use Lc\ShopBundle\Context\ProductFamilyUtilsInterface;
  18. use Lc\ShopBundle\Context\ReminderInterface;
  19. use Lc\ShopBundle\Context\TaxRateInterface;
  20. use Lc\ShopBundle\Context\UnitInterface;
  21. use Lc\ShopBundle\Context\UserInterface;
  22. use Lc\ShopBundle\Context\UserPointSaleInterface;
  23. use Liip\ImagineBundle\Imagine\Cache\CacheManager;
  24. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  25. use Symfony\Component\Form\Extension\Core\Type\HiddenType;
  26. use Symfony\Component\Form\FormBuilderInterface;
  27. use Symfony\Component\HttpClient\HttplugClient;
  28. use Symfony\Component\HttpFoundation\ParameterBag;
  29. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  30. use Symfony\Component\Validator\Constraints\EqualTo;
  31. use Symfony\Component\Validator\Constraints\NotNull;
  32. use Symfony\Contracts\Translation\TranslatorInterface;
  33. class Utils
  34. {
  35. protected $em;
  36. protected $parameterBag;
  37. protected $merchantUtils;
  38. protected $session;
  39. protected $translator;
  40. protected $configManager;
  41. const MEAN_PAYMENT_CREDIT_CARD = 'cb';
  42. const MEAN_PAYMENT_CHEQUE = 'cheque';
  43. const MEAN_PAYMENT_CREDIT = 'credit';
  44. const MEAN_PAYMENT_TRANSFER = 'transfer';
  45. const MEAN_PAYMENT_CASH = 'cash';
  46. public function __construct(EntityManagerInterface $em, ParameterBagInterface $parameterBag, SessionInterface $session, TranslatorInterface $translator, ConfigManager $configManager, CacheManager $liipCacheHelper)
  47. {
  48. $this->em = $em;
  49. $this->parameterBag = $parameterBag;
  50. $this->session = $session;
  51. $this->translator = $translator;
  52. $this->configManager = $configManager;
  53. $this->liipCacheHelper = $liipCacheHelper;
  54. }
  55. public function getElementByDevAlias($devAlias, $class = PageInterface::class)
  56. {
  57. $class = $this->em->getClassMetadata($class)->getName();
  58. return $this->em->getRepository($class)->findOneByDevAlias($devAlias);
  59. }
  60. public function isServerLocalhost()
  61. {
  62. return in_array($_SERVER['REMOTE_ADDR'], ['127.0.0.1', '::1']);
  63. }
  64. public function getCookieDomain()
  65. {
  66. return ($this->isServerLocalhost()) ? null : $this->parameterBag->get('app.cookie_domain_distant');
  67. }
  68. public function limitText($text, $limit)
  69. {
  70. $text = strip_tags($text);
  71. if (str_word_count($text, 0) > $limit) {
  72. $words = str_word_count($text, 2);
  73. $pos = array_keys($words);
  74. $text = substr($text, 0, $pos[$limit]) . '...';
  75. }
  76. return $text;
  77. }
  78. public function limitTextByLength($text, $length, $append = '...')
  79. {
  80. if(strlen($text) > $length) {
  81. $text = substr($text, 0, $length) . $append ;
  82. }
  83. return $text ;
  84. }
  85. function truncateHtml($text, $length = 100, $ending = '...', $exact = false, $considerHtml = true)
  86. {
  87. if ($considerHtml) {
  88. // if the plain text is shorter than the maximum length, return the whole text
  89. if (strlen(preg_replace('/<.*?>/', '', $text)) <= $length) {
  90. return $text;
  91. }
  92. // splits all html-tags to scanable lines
  93. preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
  94. $total_length = strlen($ending);
  95. $open_tags = array();
  96. $truncate = '';
  97. foreach ($lines as $line_matchings) {
  98. // if there is any html-tag in this line, handle it and add it (uncounted) to the output
  99. if (!empty($line_matchings[1])) {
  100. // if it's an "empty element" with or without xhtml-conform closing slash
  101. if (preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $line_matchings[1])) {
  102. // do nothing
  103. // if tag is a closing tag
  104. } else if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $line_matchings[1], $tag_matchings)) {
  105. // delete tag from $open_tags list
  106. $pos = array_search($tag_matchings[1], $open_tags);
  107. if ($pos !== false) {
  108. unset($open_tags[$pos]);
  109. }
  110. // if tag is an opening tag
  111. } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $line_matchings[1], $tag_matchings)) {
  112. // add tag to the beginning of $open_tags list
  113. array_unshift($open_tags, strtolower($tag_matchings[1]));
  114. }
  115. // add html-tag to $truncate'd text
  116. $truncate .= $line_matchings[1];
  117. }
  118. // calculate the length of the plain text part of the line; handle entities as one character
  119. $content_length = strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', ' ', $line_matchings[2]));
  120. if ($total_length + $content_length > $length) {
  121. // the number of characters which are left
  122. $left = $length - $total_length;
  123. $entities_length = 0;
  124. // search for html entities
  125. if (preg_match_all('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', $line_matchings[2], $entities, PREG_OFFSET_CAPTURE)) {
  126. // calculate the real length of all entities in the legal range
  127. foreach ($entities[0] as $entity) {
  128. if ($entity[1] + 1 - $entities_length <= $left) {
  129. $left--;
  130. $entities_length += strlen($entity[0]);
  131. } else {
  132. // no more characters left
  133. break;
  134. }
  135. }
  136. }
  137. $truncate .= substr($line_matchings[2], 0, $left + $entities_length);
  138. // maximum lenght is reached, so get off the loop
  139. break;
  140. } else {
  141. $truncate .= $line_matchings[2];
  142. $total_length += $content_length;
  143. }
  144. // if the maximum length is reached, get off the loop
  145. if ($total_length >= $length) {
  146. break;
  147. }
  148. }
  149. } else {
  150. if (strlen($text) <= $length) {
  151. return $text;
  152. } else {
  153. $truncate = substr($text, 0, $length - strlen($ending));
  154. }
  155. }
  156. // if the words shouldn't be cut in the middle...
  157. if (!$exact) {
  158. // ...search the last occurance of a space...
  159. $spacepos = strrpos($truncate, ' ');
  160. if (isset($spacepos)) {
  161. // ...and cut the text in this position
  162. $truncate = substr($truncate, 0, $spacepos);
  163. }
  164. }
  165. // add the defined ending to the text
  166. $truncate .= $ending;
  167. if ($considerHtml) {
  168. // close all unclosed html-tags
  169. foreach ($open_tags as $tag) {
  170. $truncate .= '</' . $tag . '>';
  171. }
  172. }
  173. return $truncate;
  174. }
  175. function stripAccents($stripAccents)
  176. {
  177. return strtr($stripAccents,'àáâãäçèéêëìíîïñòóôõöùúûüýÿÀÁÂÃÄÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝ','aaaaaceeeeiiiinooooouuuuyyAAAAACEEEEIIIINOOOOOUUUUY');
  178. }
  179. function cleanStringToCompare($string)
  180. {
  181. return $this->stripAccents(trim(strtolower($string))) ;
  182. }
  183. public function isBot()
  184. {
  185. if (isset($_SERVER['HTTP_USER_AGENT']) && preg_match('/bot|crawl|slurp|spider/i', $_SERVER['HTTP_USER_AGENT'])) {
  186. return TRUE;
  187. } else {
  188. return FALSE;
  189. }
  190. }
  191. public function slugify($string)
  192. {
  193. $slugify = new Slugify();
  194. return $slugify->slugify($string);
  195. }
  196. public function getUnitsList()
  197. {
  198. $unitsList = array();
  199. $units = $this->em->getRepository(UnitInterface::class)->findAll();
  200. foreach ($units as $unit) {
  201. $unitsList[$unit->getId()]['unit'] = $unit->getUnit();
  202. $unitsList[$unit->getId()]['wordingUnit'] = $unit->getWordingUnit();
  203. $unitsList[$unit->getId()]['wording'] = $unit->getWording();
  204. $unitsList[$unit->getId()]['wordingShort'] = $unit->getWordingShort();
  205. $unitsList[$unit->getId()]['coefficient'] = $unit->getCoefficient();
  206. $unitsList[$unit->getId()]['unitReference'] = $unit->getUnitReference()->getId();
  207. }
  208. return $unitsList;
  209. }
  210. public function isUserLinkedToPointSale(UserInterface $user, PointSaleInterface $pointSale)
  211. {
  212. foreach ($user->getUserPointSales() as $userPointSale) {
  213. if ($userPointSale->getPointSale()->getId() == $pointSale->getId()) {
  214. return true;
  215. }
  216. }
  217. return false;
  218. }
  219. public function linkUserToPointSale(UserInterface $user, PointSaleInterface $pointSale)
  220. {
  221. if (!$this->isUserLinkedToPointSale($user, $pointSale)) {
  222. $userPointSaleClass = $this->em->getClassMetadata(UserPointSaleInterface::class)->getName();
  223. $userPointSale = new $userPointSaleClass;
  224. $userPointSale->setUser($user);
  225. $userPointSale->setPointSale($pointSale);
  226. $this->em->persist($userPointSale);
  227. $this->em->flush();
  228. }
  229. }
  230. function callCitiesApi($method, $url, $data = false)
  231. {
  232. $url = 'https://geo.api.gouv.fr/' . $url;
  233. $curl = curl_init();
  234. switch ($method) {
  235. case "POST":
  236. curl_setopt($curl, CURLOPT_POST, 1);
  237. if ($data)
  238. curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
  239. break;
  240. case "PUT":
  241. curl_setopt($curl, CURLOPT_PUT, 1);
  242. break;
  243. default:
  244. if ($data)
  245. $url = sprintf("%s?%s", $url, http_build_query($data));
  246. }
  247. // Optional Authentication:
  248. curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
  249. curl_setopt($curl, CURLOPT_USERPWD, "username:password");
  250. curl_setopt($curl, CURLOPT_URL, $url);
  251. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  252. $result = curl_exec($curl);
  253. curl_close($curl);
  254. return $result;
  255. }
  256. public function getGeocoderProvider()
  257. {
  258. $provider = false ;
  259. $symfonyClient = new HttplugClient();
  260. $configGeocoderProvider = $this->parameterBag->get('geocoder.provider') ;
  261. /* API du gouvernement */
  262. if($configGeocoderProvider == 'addok') {
  263. $provider = new Addok($symfonyClient, 'https://api-adresse.data.gouv.fr') ;
  264. }
  265. /* Google Maps */
  266. elseif($configGeocoderProvider == 'googlemaps') {
  267. $provider = new GoogleMaps($symfonyClient, null, $this->parameterBag->get('geocoder.api_key')) ;
  268. }
  269. /* Nominatim : OpenStreetMap */
  270. elseif($configGeocoderProvider == 'nominatim') {
  271. $provider = Nominatim::withOpenStreetMapServer($symfonyClient, 'Mozilla/5.0 (platform; rv:geckoversion) Gecko/geckotrail Firefox/firefoxversion');
  272. }
  273. if(!$provider) {
  274. throw new \ErrorException('Aucun provider (geocoding) défini') ;
  275. }
  276. return $provider ;
  277. }
  278. public function callAddressApi($query)
  279. {
  280. $provider = $this->getGeocoderProvider() ;;
  281. $query = GeocodeQuery::create($query)->withData('type', 'housenumber');
  282. $results = $provider->geocodeQuery($query);
  283. $resultsToReturn = array();
  284. foreach($results as $result) {
  285. if ($result->getStreetNumber() && strlen($result->getStreetNumber()) > 0) {
  286. $resultsToReturn[] = $result;
  287. }
  288. }
  289. return $resultsToReturn;
  290. }
  291. public function callReverseAddressApi($latitude, $longitude)
  292. {
  293. $provider = $this->getGeocoderProvider() ;;
  294. $query = ReverseQuery::create(new Coordinates($latitude, $longitude));
  295. $results = $provider->reverseQuery($query);
  296. return $results->all() ;
  297. }
  298. public function getZipByCity($city, $code = null)
  299. {
  300. $zip = null;
  301. $paramsSearch = [
  302. 'nom' => $city,
  303. 'fields' => 'nom,codesPostaux'
  304. ];
  305. if ($code != null && $code != 0) {
  306. $paramsSearch['code'] = $code;
  307. }
  308. $returnCitiesSearchZip = json_decode($this->callCitiesApi('get', 'communes', $paramsSearch));
  309. if ($returnCitiesSearchZip) {
  310. foreach ($returnCitiesSearchZip as $citySearchZip) {
  311. if (strtolower(trim($city)) == strtolower(trim($citySearchZip->nom))) {
  312. $zip = $citySearchZip->codesPostaux[0];
  313. }
  314. }
  315. }
  316. return $zip;
  317. }
  318. public function date($format, $timestamp)
  319. {
  320. setlocale(LC_TIME, 'fr_FR.UTF8', 'fr.UTF8', 'fr_FR.UTF-8', 'fr.UTF-8');
  321. return strftime($format, $timestamp);
  322. }
  323. public function getNextDay($day)
  324. {
  325. return new \DateTime('next ' . $day);
  326. }
  327. public function getNextDayByNumber($number)
  328. {
  329. return $this->getNextDay($this->getDayByNumber($number, 'en'));
  330. }
  331. public function getDayByNumber($number, $lang = 'fr')
  332. {
  333. if ($lang == 'fr') {
  334. $daysArray = [
  335. 1 => 'Lundi',
  336. 2 => 'Mardi',
  337. 3 => 'Mercredi',
  338. 4 => 'Jeudi',
  339. 5 => 'Vendredi',
  340. 6 => 'Samedi',
  341. 7 => 'Dimanche'
  342. ];
  343. } else {
  344. $daysArray = [
  345. 1 => 'Monday',
  346. 2 => 'Tuesday',
  347. 3 => 'Wednesday',
  348. 4 => 'Thursday',
  349. 5 => 'Friday',
  350. 6 => 'Saturday',
  351. 7 => 'Sunday',
  352. ];
  353. }
  354. if (isset($daysArray[$number])) {
  355. return $daysArray[$number];
  356. }
  357. return '';
  358. }
  359. public function addFlash($success, $message, $extraMessages = array(), $params = array(), $domain = 'lcshop')
  360. {
  361. $message = $this->translator->trans($message, $params, $domain);
  362. if (count($extraMessages)) {
  363. $message .= '<ul>';
  364. foreach ($extraMessages as $extraMessage) {
  365. $message .= '<li> <i>' . $this->translator->trans($extraMessage, array(), $domain) . '</i></li>';
  366. }
  367. $message .= '</ul>';
  368. }
  369. $this->session->getFlashBag()->add($success, $message);
  370. }
  371. public function getFlashMessages()
  372. {
  373. return $this->session->getFlashBag()->all();
  374. }
  375. function camelCase($str)
  376. {
  377. $i = array("-", "_");
  378. $str = preg_replace('/([a-z])([A-Z])/', "\\1 \\2", $str);
  379. $str = preg_replace('@[^a-zA-Z0-9\-_ ]+@', '', $str);
  380. $str = str_replace($i, ' ', $str);
  381. $str = str_replace(' ', '', ucwords(strtolower($str)));
  382. $str = strtolower(substr($str, 0, 1)) . substr($str, 1);
  383. return $str;
  384. }
  385. function snakeCase($str)
  386. {
  387. $str = preg_replace('/([a-z])([A-Z])/', "\\1_\\2", $str);
  388. $str = strtolower($str);
  389. return $str;
  390. }
  391. public function csvEscape($str)
  392. {
  393. return str_replace(array("\r", "\n"), ' ', $str);
  394. }
  395. public function getRemindersByUser($user)
  396. {
  397. $reminderRepo = $this->em->getRepository(ReminderInterface::class);
  398. $reminders = $reminderRepo->findByUser($user);
  399. $entitiesRepo = array();
  400. $entitiesConfig = array();
  401. if (count($reminders) > 0) {
  402. foreach ($reminders as $reminder) {
  403. if ($reminder->getEntityName()) {
  404. if (!isset($entitiesConfig[$reminder->getEntityName()])) {
  405. $entitiesConfig[$reminder->getEntityName()] = $this->configManager->getEntityConfig($reminder->getEntityName());
  406. }
  407. if ($reminder->getEntityAction() == 'edit' || $reminder->getEntityAction() == 'show') {
  408. if (!isset($entitiesRepo[$reminder->getEntityName()])) {
  409. $entitiesRepo[$reminder->getEntityName()] = $this->em->getRepository($entitiesConfig[$reminder->getEntityName()]['class']);
  410. }
  411. if ($reminder->getEntityId()) {
  412. $reminder->relatedPage = $entitiesRepo[$reminder->getEntityName()]->find($reminder->getEntityId())->__toString();
  413. }
  414. } else {
  415. $reminder->relatedPage = 'Liste de ' . $entitiesConfig[$reminder->getEntityName()]['label'];
  416. }
  417. }
  418. }
  419. }
  420. return $reminders;
  421. }
  422. public function removeDir($dir)
  423. {
  424. $files = array_diff(scandir($dir), array('.', '..'));
  425. foreach ($files as $file) {
  426. (is_dir("$dir/$file")) ? $this->removeDir("$dir/$file") : unlink("$dir/$file");
  427. }
  428. return rmdir($dir);
  429. }
  430. function folderToZip($folder, &$zipFile, $subfolder = null)
  431. {
  432. if ($zipFile == null) {
  433. // no resource given, exit
  434. return false;
  435. }
  436. // we check if $folder has a slash at its end, if not, we append one
  437. $tabFolder = str_split($folder);
  438. $tabSubFolder = str_split($subfolder);
  439. $folder .= end($tabFolder) == "/" ? "" : "/";
  440. $subfolder .= end($tabSubFolder) == "/" ? "" : "/";
  441. // we start by going through all files in $folder
  442. $handle = opendir($folder);
  443. while ($f = readdir($handle)) {
  444. if ($f != "." && $f != "..") {
  445. if (is_file($folder . $f)) {
  446. // if we find a file, store it
  447. // if we have a subfolder, store it there
  448. if ($subfolder != null)
  449. $zipFile->addFile($folder . $f, $subfolder . $f);
  450. else
  451. $zipFile->addFile($folder . $f);
  452. } elseif (is_dir($folder . $f)) {
  453. // if we find a folder, create a folder in the zip
  454. $zipFile->addEmptyDir($f);
  455. // and call the function again
  456. folderToZip($folder . $f, $zipFile, $f);
  457. }
  458. }
  459. }
  460. }
  461. public function lcLiip($path, $thumb = 'tile', $default = 'default.jpg')
  462. {
  463. if (substr($path, 0, 1) === '/') $path = substr($path, 1);
  464. if ($path) {
  465. $fileManagerFolder = substr($this->getFileManagerFolder(), 1) ;
  466. if (strpos($path, $fileManagerFolder) === false) {
  467. $path = $fileManagerFolder . '/' . $path;
  468. }
  469. if (file_exists($path)) {
  470. return $this->liipCacheHelper->getBrowserPath($path, $thumb);
  471. }
  472. }
  473. return $this->liipCacheHelper->getBrowserPath($this->getFileManagerFolder() . '/' . $default, $thumb);
  474. }
  475. /**
  476. * Retourne le chemin vers le dossier d'uploads de responsiveFilemanager
  477. *
  478. * @return string
  479. */
  480. public function getFileManagerFolder()
  481. {
  482. return $this->parameterBag->get('app.path.images');
  483. }
  484. public function addCaptchaType(FormBuilderInterface $builder)
  485. {
  486. $builder->add('specialField', HiddenType::class, [
  487. 'data' => 0,
  488. 'mapped' => false,
  489. 'attr' => [
  490. 'class' => 'special-field'
  491. ],
  492. 'constraints' => [
  493. new NotNull(),
  494. new EqualTo(['value' => $this->parameterBag->get('app.captcha_value'), 'message' => 'Valeur incorrecte'])
  495. ],
  496. ]);
  497. }
  498. public function urlEncryptData($datas){
  499. $key = 'secretToken';
  500. foreach ($datas as $data) {
  501. $key .= $data;
  502. }
  503. return md5($key);
  504. }
  505. public function getFilterPropertyClean($fieldName){
  506. return str_replace('.', '_', $fieldName);
  507. }
  508. public function getFilterPropertyInit($fieldName){
  509. return str_replace('_', '.', $fieldName);
  510. }
  511. public function hasFilterAssociation($fieldName, $needle="."){
  512. return strpos($fieldName, $needle);
  513. }
  514. public function getFilterWithoutAssociationAlias($fieldName, $needle = '.'){
  515. return substr($fieldName, strpos($fieldName, $needle)+1);
  516. }
  517. public function getFilterAssociationAlias($fieldName, $needle = '.'){
  518. return substr($fieldName, 0, strpos($fieldName, $needle));
  519. }
  520. public function round($price, $precision = 2)
  521. {
  522. return round((($price * 100)) / 100, $precision);
  523. }
  524. }