You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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