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.

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