Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

vor 4 Jahren
vor 4 Jahren
vor 4 Jahren
vor 4 Jahren
vor 4 Jahren
vor 4 Jahren
vor 4 Jahren
vor 4 Jahren
vor 4 Jahren
vor 4 Jahren
vor 4 Jahren
vor 4 Jahren
vor 4 Jahren
vor 4 Jahren
vor 4 Jahren
vor 4 Jahren
vor 4 Jahren
vor 4 Jahren
vor 4 Jahren
vor 4 Jahren
vor 4 Jahren
vor 4 Jahren
vor 4 Jahren
vor 4 Jahren
vor 4 Jahren
vor 4 Jahren
vor 4 Jahren
vor 4 Jahren
vor 4 Jahren
vor 4 Jahren
vor 4 Jahren
vor 4 Jahren
vor 4 Jahren
vor 4 Jahren
vor 4 Jahren
vor 4 Jahren
vor 4 Jahren
vor 4 Jahren
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  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. public function isBot()
  165. {
  166. if (isset($_SERVER['HTTP_USER_AGENT']) && preg_match('/bot|crawl|slurp|spider/i', $_SERVER['HTTP_USER_AGENT'])) {
  167. return TRUE;
  168. } else {
  169. return FALSE;
  170. }
  171. }
  172. public function slugify($string)
  173. {
  174. $slugify = new Slugify();
  175. return $slugify->slugify($string);
  176. }
  177. public function getUnitsList()
  178. {
  179. $unitsList = array();
  180. $units = $this->em->getRepository(UnitInterface::class)->findAll();
  181. foreach ($units as $unit) {
  182. $unitsList[$unit->getId()]['unit'] = $unit->getUnit();
  183. $unitsList[$unit->getId()]['wordingUnit'] = $unit->getWordingUnit();
  184. $unitsList[$unit->getId()]['wording'] = $unit->getWording();
  185. $unitsList[$unit->getId()]['wordingShort'] = $unit->getWordingShort();
  186. $unitsList[$unit->getId()]['coefficient'] = $unit->getCoefficient();
  187. $unitsList[$unit->getId()]['unitReference'] = $unit->getUnitReference()->getId();
  188. }
  189. return $unitsList;
  190. }
  191. public function isUserLinkedToPointSale(UserInterface $user, PointSaleInterface $pointSale)
  192. {
  193. foreach ($user->getUserPointSales() as $userPointSale) {
  194. if ($userPointSale->getPointSale()->getId() == $pointSale->getId()) {
  195. return true;
  196. }
  197. }
  198. return false;
  199. }
  200. public function linkUserToPointSale(UserInterface $user, PointSaleInterface $pointSale)
  201. {
  202. if (!$this->isUserLinkedToPointSale($user, $pointSale)) {
  203. $userPointSaleClass = $this->em->getClassMetadata(UserPointSaleInterface::class)->getName();
  204. $userPointSale = new $userPointSaleClass;
  205. $userPointSale->setUser($user);
  206. $userPointSale->setPointSale($pointSale);
  207. $this->em->persist($userPointSale);
  208. $this->em->flush();
  209. }
  210. }
  211. function callCitiesApi($method, $url, $data = false)
  212. {
  213. $url = 'https://geo.api.gouv.fr/' . $url;
  214. $curl = curl_init();
  215. switch ($method) {
  216. case "POST":
  217. curl_setopt($curl, CURLOPT_POST, 1);
  218. if ($data)
  219. curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
  220. break;
  221. case "PUT":
  222. curl_setopt($curl, CURLOPT_PUT, 1);
  223. break;
  224. default:
  225. if ($data)
  226. $url = sprintf("%s?%s", $url, http_build_query($data));
  227. }
  228. // Optional Authentication:
  229. curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
  230. curl_setopt($curl, CURLOPT_USERPWD, "username:password");
  231. curl_setopt($curl, CURLOPT_URL, $url);
  232. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  233. $result = curl_exec($curl);
  234. curl_close($curl);
  235. return $result;
  236. }
  237. public function getGeocoderProvider()
  238. {
  239. $provider = false ;
  240. $symfonyClient = new HttplugClient();
  241. $configGeocoderProvider = $this->parameterBag->get('geocoder.provider') ;
  242. /* API du gouvernement */
  243. if($configGeocoderProvider == 'addok') {
  244. $provider = new Addok($symfonyClient, 'https://api-adresse.data.gouv.fr') ;
  245. }
  246. /* Google Maps */
  247. elseif($configGeocoderProvider == 'googlemaps') {
  248. $provider = new GoogleMaps($symfonyClient, null, $this->parameterBag->get('geocoder.api_key')) ;
  249. }
  250. /* Nominatim : OpenStreetMap */
  251. elseif($configGeocoderProvider == 'nominatim') {
  252. $provider = Nominatim::withOpenStreetMapServer($symfonyClient, 'Mozilla/5.0 (platform; rv:geckoversion) Gecko/geckotrail Firefox/firefoxversion');
  253. }
  254. if(!$provider) {
  255. throw new \ErrorException('Aucun provider (geocoding) défini') ;
  256. }
  257. return $provider ;
  258. }
  259. public function callAddressApi($query)
  260. {
  261. $provider = $this->getGeocoderProvider() ;;
  262. $query = GeocodeQuery::create($query)->withData('type', 'housenumber');
  263. $results = $provider->geocodeQuery($query);
  264. return $results->all() ;
  265. }
  266. public function callReverseAddressApi($latitude, $longitude)
  267. {
  268. $provider = $this->getGeocoderProvider() ;;
  269. $query = ReverseQuery::create(new Coordinates($latitude, $longitude));
  270. $results = $provider->reverseQuery($query);
  271. return $results->all() ;
  272. }
  273. public function getZipByCity($city, $code = null)
  274. {
  275. $zip = null;
  276. $paramsSearch = [
  277. 'nom' => $city,
  278. 'fields' => 'nom,codesPostaux'
  279. ];
  280. if ($code != null && $code != 0) {
  281. $paramsSearch['code'] = $code;
  282. }
  283. $returnCitiesSearchZip = json_decode($this->callCitiesApi('get', 'communes', $paramsSearch));
  284. if ($returnCitiesSearchZip) {
  285. foreach ($returnCitiesSearchZip as $citySearchZip) {
  286. if (strtolower(trim($city)) == strtolower(trim($citySearchZip->nom))) {
  287. $zip = $citySearchZip->codesPostaux[0];
  288. }
  289. }
  290. }
  291. return $zip;
  292. }
  293. public function date($format, $timestamp)
  294. {
  295. setlocale(LC_TIME, 'fr_FR.UTF8', 'fr.UTF8', 'fr_FR.UTF-8', 'fr.UTF-8');
  296. return strftime($format, $timestamp);
  297. }
  298. public function getNextDay($day)
  299. {
  300. return new \DateTime('next ' . $day);
  301. }
  302. public function getNextDayByNumber($number)
  303. {
  304. return $this->getNextDay($this->getDayByNumber($number, 'en'));
  305. }
  306. public function getDayByNumber($number, $lang = 'fr')
  307. {
  308. if ($lang == 'fr') {
  309. $daysArray = [
  310. 1 => 'Lundi',
  311. 2 => 'Mardi',
  312. 3 => 'Mercredi',
  313. 4 => 'Jeudi',
  314. 5 => 'Vendredi',
  315. 6 => 'Samedi',
  316. 7 => 'Dimanche'
  317. ];
  318. } else {
  319. $daysArray = [
  320. 1 => 'Monday',
  321. 2 => 'Tuesday',
  322. 3 => 'Wednesday',
  323. 4 => 'Thursday',
  324. 5 => 'Friday',
  325. 6 => 'Saturday',
  326. 7 => 'Sunday',
  327. ];
  328. }
  329. if (isset($daysArray[$number])) {
  330. return $daysArray[$number];
  331. }
  332. return '';
  333. }
  334. public function addFlash($success, $message, $extraMessages = array(), $params = array(), $domain = 'lcshop')
  335. {
  336. $message = $this->translator->trans($message, $params, $domain);
  337. if (count($extraMessages)) {
  338. $message .= '<ul>';
  339. foreach ($extraMessages as $extraMessage) {
  340. $message .= '<li> <i>' . $this->translator->trans($extraMessage, array(), $domain) . '</i></li>';
  341. }
  342. $message .= '</ul>';
  343. }
  344. $this->session->getFlashBag()->add($success, $message);
  345. }
  346. public function getFlashMessages()
  347. {
  348. return $this->session->getFlashBag()->all();
  349. }
  350. function camelCase($str)
  351. {
  352. $i = array("-", "_");
  353. $str = preg_replace('/([a-z])([A-Z])/', "\\1 \\2", $str);
  354. $str = preg_replace('@[^a-zA-Z0-9\-_ ]+@', '', $str);
  355. $str = str_replace($i, ' ', $str);
  356. $str = str_replace(' ', '', ucwords(strtolower($str)));
  357. $str = strtolower(substr($str, 0, 1)) . substr($str, 1);
  358. return $str;
  359. }
  360. function snakeCase($str)
  361. {
  362. $str = preg_replace('/([a-z])([A-Z])/', "\\1_\\2", $str);
  363. $str = strtolower($str);
  364. return $str;
  365. }
  366. public function csvEscape($str)
  367. {
  368. return str_replace(array("\r", "\n"), ' ', $str);
  369. }
  370. public function getRemindersByUser($user)
  371. {
  372. $reminderRepo = $this->em->getRepository(ReminderInterface::class);
  373. $reminders = $reminderRepo->findByUser($user);
  374. $entitiesRepo = array();
  375. $entitiesConfig = array();
  376. if (count($reminders) > 0) {
  377. foreach ($reminders as $reminder) {
  378. if ($reminder->getEntityName()) {
  379. if (!isset($entitiesConfig[$reminder->getEntityName()])) {
  380. $entitiesConfig[$reminder->getEntityName()] = $this->configManager->getEntityConfig($reminder->getEntityName());
  381. }
  382. if ($reminder->getEntityAction() == 'edit' || $reminder->getEntityAction() == 'show') {
  383. if (!isset($entitiesRepo[$reminder->getEntityName()])) {
  384. $entitiesRepo[$reminder->getEntityName()] = $this->em->getRepository($entitiesConfig[$reminder->getEntityName()]['class']);
  385. }
  386. if ($reminder->getEntityId()) {
  387. $reminder->relatedPage = $entitiesRepo[$reminder->getEntityName()]->find($reminder->getEntityId())->__toString();
  388. }
  389. } else {
  390. $reminder->relatedPage = 'Liste de ' . $entitiesConfig[$reminder->getEntityName()]['label'];
  391. }
  392. }
  393. }
  394. }
  395. return $reminders;
  396. }
  397. public function removeDir($dir)
  398. {
  399. $files = array_diff(scandir($dir), array('.', '..'));
  400. foreach ($files as $file) {
  401. (is_dir("$dir/$file")) ? $this->removeDir("$dir/$file") : unlink("$dir/$file");
  402. }
  403. return rmdir($dir);
  404. }
  405. function folderToZip($folder, &$zipFile, $subfolder = null)
  406. {
  407. if ($zipFile == null) {
  408. // no resource given, exit
  409. return false;
  410. }
  411. // we check if $folder has a slash at its end, if not, we append one
  412. $tabFolder = str_split($folder);
  413. $tabSubFolder = str_split($subfolder);
  414. $folder .= end($tabFolder) == "/" ? "" : "/";
  415. $subfolder .= end($tabSubFolder) == "/" ? "" : "/";
  416. // we start by going through all files in $folder
  417. $handle = opendir($folder);
  418. while ($f = readdir($handle)) {
  419. if ($f != "." && $f != "..") {
  420. if (is_file($folder . $f)) {
  421. // if we find a file, store it
  422. // if we have a subfolder, store it there
  423. if ($subfolder != null)
  424. $zipFile->addFile($folder . $f, $subfolder . $f);
  425. else
  426. $zipFile->addFile($folder . $f);
  427. } elseif (is_dir($folder . $f)) {
  428. // if we find a folder, create a folder in the zip
  429. $zipFile->addEmptyDir($f);
  430. // and call the function again
  431. folderToZip($folder . $f, $zipFile, $f);
  432. }
  433. }
  434. }
  435. }
  436. public function lcLiip($path, $thumb = 'tile', $default = 'default.jpg')
  437. {
  438. if (substr($path, 0, 1) === '/') $path = substr($path, 1);
  439. if ($path) {
  440. $fileManagerFolder = substr($this->getFileManagerFolder(), 1) ;
  441. if (strpos($path, $fileManagerFolder) === false) {
  442. $path = $fileManagerFolder . '/' . $path;
  443. }
  444. if (file_exists($path)) {
  445. return $this->liipCacheHelper->getBrowserPath($path, $thumb);
  446. }
  447. }
  448. return $this->liipCacheHelper->getBrowserPath($this->getFileManagerFolder() . '/' . $default, $thumb);
  449. }
  450. /**
  451. * Retourne le chemin vers le dossier d'uploads de responsiveFilemanager
  452. *
  453. * @return string
  454. */
  455. public function getFileManagerFolder()
  456. {
  457. return $this->parameterBag->get('app.path.images');
  458. }
  459. }