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.

523 lines
23KB

  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. $symfonyClient = new HttplugClient();
  240. /* API du gouvernement */
  241. $provider = new Addok($symfonyClient, 'https://api-adresse.data.gouv.fr') ;
  242. /* Google Maps */
  243. //$provider = new GoogleMaps($symfonyClient, null, '') ;
  244. /* Nominatim : OpenStreetMap */
  245. //$provider = Nominatim::withOpenStreetMapServer($symfonyClient, 'Mozilla/5.0 (platform; rv:geckoversion) Gecko/geckotrail Firefox/firefoxversion');
  246. return $provider ;
  247. }
  248. public function callAddressApi($query)
  249. {
  250. $provider = $this->getGeocoderProvider() ;;
  251. $query = GeocodeQuery::create($query)->withData('type', 'housenumber');
  252. $results = $provider->geocodeQuery($query);
  253. return $results->all() ;
  254. }
  255. public function callReverseAddressApi($latitude, $longitude)
  256. {
  257. $provider = $this->getGeocoderProvider() ;;
  258. $query = ReverseQuery::create(new Coordinates($latitude, $longitude));
  259. $results = $provider->reverseQuery($query);
  260. return $results->all() ;
  261. }
  262. public function getZipByCity($city, $code = null)
  263. {
  264. $zip = null;
  265. $paramsSearch = [
  266. 'nom' => $city,
  267. 'fields' => 'nom,codesPostaux'
  268. ];
  269. if ($code != null && $code != 0) {
  270. $paramsSearch['code'] = $code;
  271. }
  272. $returnCitiesSearchZip = json_decode($this->callCitiesApi('get', 'communes', $paramsSearch));
  273. if ($returnCitiesSearchZip) {
  274. foreach ($returnCitiesSearchZip as $citySearchZip) {
  275. if (strtolower(trim($city)) == strtolower(trim($citySearchZip->nom))) {
  276. $zip = $citySearchZip->codesPostaux[0];
  277. }
  278. }
  279. }
  280. return $zip;
  281. }
  282. public function date($format, $timestamp)
  283. {
  284. setlocale(LC_TIME, 'fr_FR.UTF8', 'fr.UTF8', 'fr_FR.UTF-8', 'fr.UTF-8');
  285. return strftime($format, $timestamp);
  286. }
  287. public function getNextDay($day)
  288. {
  289. return new \DateTime('next ' . $day);
  290. }
  291. public function getNextDayByNumber($number)
  292. {
  293. return $this->getNextDay($this->getDayByNumber($number, 'en'));
  294. }
  295. public function getDayByNumber($number, $lang = 'fr')
  296. {
  297. if ($lang == 'fr') {
  298. $daysArray = [
  299. 1 => 'Lundi',
  300. 2 => 'Mardi',
  301. 3 => 'Mercredi',
  302. 4 => 'Jeudi',
  303. 5 => 'Vendredi',
  304. 6 => 'Samedi',
  305. 7 => 'Dimanche'
  306. ];
  307. } else {
  308. $daysArray = [
  309. 1 => 'Monday',
  310. 2 => 'Tuesday',
  311. 3 => 'Wednesday',
  312. 4 => 'Thursday',
  313. 5 => 'Friday',
  314. 6 => 'Saturday',
  315. 7 => 'Sunday',
  316. ];
  317. }
  318. if (isset($daysArray[$number])) {
  319. return $daysArray[$number];
  320. }
  321. return '';
  322. }
  323. public function addFlash($success, $message, $extraMessages = array(), $params = array(), $domain = 'lcshop')
  324. {
  325. $message = $this->translator->trans($message, $params, $domain);
  326. if (count($extraMessages)) {
  327. $message .= '<ul>';
  328. foreach ($extraMessages as $extraMessage) {
  329. $message .= '<li> <i>' . $this->translator->trans($extraMessage, array(), $domain) . '</i></li>';
  330. }
  331. $message .= '</ul>';
  332. }
  333. $this->session->getFlashBag()->add($success, $message);
  334. }
  335. public function getFlashMessages()
  336. {
  337. return $this->session->getFlashBag()->all();
  338. }
  339. function camelCase($str)
  340. {
  341. $i = array("-", "_");
  342. $str = preg_replace('/([a-z])([A-Z])/', "\\1 \\2", $str);
  343. $str = preg_replace('@[^a-zA-Z0-9\-_ ]+@', '', $str);
  344. $str = str_replace($i, ' ', $str);
  345. $str = str_replace(' ', '', ucwords(strtolower($str)));
  346. $str = strtolower(substr($str, 0, 1)) . substr($str, 1);
  347. return $str;
  348. }
  349. function snakeCase($str)
  350. {
  351. $str = preg_replace('/([a-z])([A-Z])/', "\\1_\\2", $str);
  352. $str = strtolower($str);
  353. return $str;
  354. }
  355. public function csvEscape($str)
  356. {
  357. return str_replace(array("\r", "\n"), ' ', $str);
  358. }
  359. public function getRemindersByUser($user)
  360. {
  361. $reminderRepo = $this->em->getRepository(ReminderInterface::class);
  362. $reminders = $reminderRepo->findByUser($user);
  363. $entitiesRepo = array();
  364. $entitiesConfig = array();
  365. if (count($reminders) > 0) {
  366. foreach ($reminders as $reminder) {
  367. if ($reminder->getEntityName()) {
  368. if (!isset($entitiesConfig[$reminder->getEntityName()])) {
  369. $entitiesConfig[$reminder->getEntityName()] = $this->configManager->getEntityConfig($reminder->getEntityName());
  370. }
  371. if ($reminder->getEntityAction() == 'edit' || $reminder->getEntityAction() == 'show') {
  372. if (!isset($entitiesRepo[$reminder->getEntityName()])) {
  373. $entitiesRepo[$reminder->getEntityName()] = $this->em->getRepository($entitiesConfig[$reminder->getEntityName()]['class']);
  374. }
  375. if ($reminder->getEntityId()) {
  376. $reminder->relatedPage = $entitiesRepo[$reminder->getEntityName()]->find($reminder->getEntityId())->__toString();
  377. }
  378. } else {
  379. $reminder->relatedPage = 'Liste de ' . $entitiesConfig[$reminder->getEntityName()]['label'];
  380. }
  381. }
  382. }
  383. }
  384. return $reminders;
  385. }
  386. public function removeDir($dir)
  387. {
  388. $files = array_diff(scandir($dir), array('.', '..'));
  389. foreach ($files as $file) {
  390. (is_dir("$dir/$file")) ? $this->removeDir("$dir/$file") : unlink("$dir/$file");
  391. }
  392. return rmdir($dir);
  393. }
  394. function folderToZip($folder, &$zipFile, $subfolder = null)
  395. {
  396. if ($zipFile == null) {
  397. // no resource given, exit
  398. return false;
  399. }
  400. // we check if $folder has a slash at its end, if not, we append one
  401. $tabFolder = str_split($folder);
  402. $tabSubFolder = str_split($subfolder);
  403. $folder .= end($tabFolder) == "/" ? "" : "/";
  404. $subfolder .= end($tabSubFolder) == "/" ? "" : "/";
  405. // we start by going through all files in $folder
  406. $handle = opendir($folder);
  407. while ($f = readdir($handle)) {
  408. if ($f != "." && $f != "..") {
  409. if (is_file($folder . $f)) {
  410. // if we find a file, store it
  411. // if we have a subfolder, store it there
  412. if ($subfolder != null)
  413. $zipFile->addFile($folder . $f, $subfolder . $f);
  414. else
  415. $zipFile->addFile($folder . $f);
  416. } elseif (is_dir($folder . $f)) {
  417. // if we find a folder, create a folder in the zip
  418. $zipFile->addEmptyDir($f);
  419. // and call the function again
  420. folderToZip($folder . $f, $zipFile, $f);
  421. }
  422. }
  423. }
  424. }
  425. public function lcLiip($path, $thumb = 'tile', $default = 'default.jpg')
  426. {
  427. if (substr($path, 0, 1) === '/') $path = substr($path, 1);
  428. if ($path) {
  429. $fileManagerFolder = substr($this->getFileManagerFolder(), 1) ;
  430. if (strpos($path, $fileManagerFolder) === false) {
  431. $path = $fileManagerFolder . '/' . $path;
  432. }
  433. if (file_exists($path)) {
  434. return $this->liipCacheHelper->getBrowserPath($path, $thumb);
  435. }
  436. }
  437. return $this->liipCacheHelper->getBrowserPath($this->getFileManagerFolder() . '/' . $default, $thumb);
  438. }
  439. /**
  440. * Retourne le chemin vers le dossier d'uploads de responsiveFilemanager
  441. *
  442. * @return string
  443. */
  444. public function getFileManagerFolder()
  445. {
  446. return $this->parameterBag->get('app.path.images');
  447. }
  448. }