Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

506 lines
22KB

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