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