Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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