src/Controller/FrontEnd/FormHandlerController.php line 77

Open in your IDE?
  1. <?php
  2. namespace App\Controller\FrontEnd;
  3. use App\Entity\Post;
  4. use App\Entity\User;
  5. use App\Entity\Forms;
  6. use App\Entity\Country;
  7. use App\Entity\Commande;
  8. use App\Entity\FormsData;
  9. use App\Entity\FormsFields;
  10. use App\Twig\CryptExtension;
  11. use App\Entity\ParametreSite;
  12. use App\Service\EmailService;
  13. use App\Entity\CommandeLignes;
  14. use App\Entity\FormsTranslation;
  15. use App\Service\EncryptionService;
  16. use Symfony\Component\Intl\Locale;
  17. use Doctrine\ORM\EntityManagerInterface;
  18. use Symfony\Component\Filesystem\Filesystem;
  19. use Symfony\Component\HttpFoundation\Request;
  20. use Symfony\Component\HttpFoundation\Response;
  21. use Symfony\Component\Routing\Annotation\Route;
  22. use Symfony\Component\HttpClient\CurlHttpClient;
  23. use Symfony\Component\HttpFoundation\JsonResponse;
  24. use Symfony\Contracts\HttpClient\HttpClientInterface;
  25. use Symfony\Component\String\Slugger\SluggerInterface;
  26. use Symfony\Component\Translation\TranslatorInterface;
  27. use Symfony\Component\Mime\Part\Multipart\FormDataPart;
  28. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  29. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  30. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  31. class FormHandlerController extends AbstractController
  32. {
  33. private $theme;
  34. private $emailService;
  35. private $projectDir;
  36. private $formUploadDir;
  37. private $slugger;
  38. private $encryptionService;
  39. private $em;
  40. private $client;
  41. private $cryptExtension;
  42. protected $session;
  43. private $parameterBag;
  44. public function __construct(string $theme,string $projectDir,string $formUploadDir,
  45. HttpClientInterface $client,
  46. ParameterBagInterface $parameterBag,
  47. EmailService $emailService,
  48. EntityManagerInterface $em,
  49. SluggerInterface $slugger,
  50. EncryptionService $encryptionService,
  51. SessionInterface $session,
  52. CryptExtension $cryptExtension){
  53. $this->theme = $theme;
  54. $this->emailService = $emailService;
  55. $this->projectDir = $projectDir;
  56. $this->formUploadDir = $formUploadDir;
  57. $this->slugger = $slugger;
  58. $this->encryptionService = $encryptionService;
  59. $this->em = $em;
  60. $this->session = $session;
  61. $this->client = $client;
  62. $this->cryptExtension = $cryptExtension;
  63. $this->parameterBag = $parameterBag;
  64. }
  65. /**
  66. * @Route("/api/submit-request", methods={"POST"} ,name="submit_request")
  67. */
  68. public function index(Request $request)
  69. {
  70. $_locale = $request->getLocale();
  71. $parametre = $this->em->getRepository(ParametreSite::class)->findOneBy([],['id'=> 'ASC']);
  72. $recaptchaGoogle = $request->request->get('g-recaptcha-response');
  73. $csrfToken = $request->request->get('token_id');
  74. $formId = $this->cryptExtension->decryptValue($request->request->get('form-id'));
  75. $data = $request->request->all();
  76. $files = $request->files->all();
  77. if (!$this->isCsrfTokenValid('form_handler', $csrfToken)) {
  78. return new JsonResponse(['status' => 'erreur','message' => 'Token CSRF du formulaire invalide.']);
  79. }
  80. $app_env = $this->parameterBag->get('APP_ENV');
  81. $fichiers = !empty($files) ? $this->processUpload($files):[];
  82. try {
  83. if($app_env != 'dev'){
  84. if (!$recaptchaGoogle) {
  85. return new JsonResponse(['status' => 'erreur','message' => 'reCAPTCHA invalide.']);
  86. }
  87. $response = $this->client->request('POST', 'https://www.google.com/recaptcha/api/siteverify', [
  88. 'body' => ['secret' => $parametre->getCleSecret(),'response' => $recaptchaGoogle]
  89. ]);
  90. $responseKeys = $response->toArray();
  91. if (empty($responseKeys['success']) || !$responseKeys['success']) {
  92. return new JsonResponse(['status' => 'erreur','message' => 'reCAPTCHA invalide.']);
  93. }
  94. if ($parametre->getTypeRecaptcha() == 1 && $responseKeys['score'] < 0.3) {
  95. return new JsonResponse(['status' => 'erreur','message' => 'Score reCAPTCHA faible.']);
  96. }
  97. }
  98. $formulaire = $this->em->getRepository(Forms::class)->findOneBy(['id'=> $formId]);
  99. if($formulaire){
  100. $methode = $formulaire->getMethode();
  101. $formField = $this->em->getRepository(FormsFields::class)->findOneBy(['form'=> $formulaire,'local'=> $_locale]);
  102. $message_sucess = $formulaire->translate($_locale)->getSuccessMessage() ?? 'Votre formulaire a été soumis avec succès.';
  103. if($formField){
  104. $fields = unserialize($formField->getData());
  105. }
  106. $data_form = $this->filterDataForm($data,$fields);
  107. $email_user = isset($data['email']) ? $data['email']:null;
  108. switch ($methode) {
  109. case 'database':
  110. $formsData = new FormsData();
  111. $formsData->setForm($formulaire);
  112. $formsData->setData(serialize($data));
  113. $formsData->setFiles(serialize($fichiers));
  114. $formsData->setLocal($_locale);
  115. $this->em->persist($formsData);
  116. $this->em->flush();
  117. break;
  118. case 'database_email':
  119. $formsData = new FormsData();
  120. $formsData->setForm($formulaire);
  121. $formsData->setData(serialize($data));
  122. $formsData->setFiles(serialize($fichiers));
  123. $formsData->setLocal($_locale);
  124. $this->em->persist($formsData);
  125. $this->em->flush();
  126. if($formulaire->getEmail()){
  127. $emails = unserialize($formulaire->getEmail());
  128. $this->emailService->sendEmailForm($formulaire->getEmailSubject(),$emails,$email_user,$data_form,$fichiers);
  129. }
  130. break;
  131. case 'email':
  132. if($formulaire->getEmail()){
  133. $emails = unserialize($formulaire->getEmail());
  134. $this->emailService->sendEmailForm($formulaire->getEmailSubject(),$emails,$email_user,$data_form,$fichiers);
  135. }
  136. break;
  137. }
  138. }
  139. return new JsonResponse(['status' => 'success','message' => $message_sucess]);
  140. } catch (\Exception $e) {
  141. return new JsonResponse(['status' => 'erreur','message' => 'Erreur lors de la vérification du reCAPTCHA.', 'details' => $e->getMessage()]);
  142. }
  143. }
  144. public function filterDataForm($dataForm,$fields,$fichiers = null){
  145. $data = [];
  146. $locale = Locale::getDefault();
  147. $em = $this->getDoctrine()->getManager();
  148. $protocol = isset($_SERVER['HTTPS']) ? 'https://' : 'http://';
  149. $index = 0;
  150. if(isset($dataForm['id_etablissement'])){
  151. $etablisement = $em->getRepository(Post::class)->find($dataForm['id_etablissement']);
  152. if($etablisement){
  153. $data[$index]['type'] = 'etablissment';
  154. $data[$index]['label'] = 'Réservation';
  155. $data[$index]['value'] = 'Je voudrais faire une réservation au '.$etablisement->translate($locale)->getTitle();
  156. $index++;
  157. }
  158. }
  159. if ($fields) {
  160. foreach ($fields as $value) {
  161. if($value){
  162. foreach($value as $field){
  163. if($field['type'] != 'header' && $field['name'] != 'check-condition'){
  164. if($field['type'] != 'file'){
  165. if(isset($field['name']) && isset($dataForm[str_replace("[]","",$field['name'])])){
  166. if (isset($field['label'])) {
  167. if ($field['label'] != '') {
  168. $label = $field['label'];
  169. }
  170. }elseif(isset($field['placeholder'])){
  171. if ($field['placeholder'] != ''){
  172. $label = $field['placeholder'];
  173. }
  174. }else{
  175. $label = null;
  176. }
  177. $data[$index]['type'] = $field['type'];
  178. $data[$index]['label'] = $label;
  179. $data[$index]['value'] = $dataForm[str_replace("[]","",$field['name'])];
  180. }
  181. $index++;
  182. }else{
  183. if ($fichiers) {
  184. foreach($fichiers as $fichier){
  185. if(isset($field['name']) && isset($fichier['name']) && ($field['name'] == $fichier['name']) && isset($fichier['value'])){
  186. if (isset($field['label'])) {
  187. if ($field['label'] != '') {
  188. $label = $field['label'];
  189. }
  190. }else{
  191. $label = null;
  192. }
  193. $data[$index]['type'] = $field['type'];
  194. $data[$index]['label'] = $label;
  195. $data[$index]['value'] = $protocol.$fichier[str_replace("[]","",'value')];
  196. }
  197. $index++;
  198. }
  199. }
  200. }
  201. }
  202. }
  203. }
  204. }
  205. }
  206. return $data;
  207. }
  208. public function processUpload(array $files): array
  209. {
  210. $uploadedFiles = [];
  211. $allowedTypes = ['pdf', 'doc', 'docx', 'txt', 'jpg', 'jpeg', 'png'];
  212. $maxFileSize = 2048 * 1024; // 2 MB
  213. foreach ($files['files'] as $file) {
  214. if (!$file) {
  215. continue;
  216. }
  217. $fileSize = $file->getSize();
  218. $fileExtension = $file->guessExtension();
  219. if (!in_array($fileExtension, $allowedTypes) || $fileSize > $maxFileSize) {
  220. continue;
  221. }
  222. $originalFilename = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
  223. $safeFilename = $this->slugger->slug($originalFilename);
  224. $uniqueId = hash('sha256', uniqid((string) mt_rand(), true));
  225. $newFilename = sprintf('%s-%s.%s', $safeFilename, $uniqueId, $fileExtension);
  226. $uploadPath = $this->formUploadDir . '/' . $newFilename;
  227. if (file_exists($file->getRealPath())) {
  228. move_uploaded_file($file->getRealPath(), $uploadPath);
  229. $uploadedFiles[] = '/uploads/form-files/' . $newFilename;
  230. }
  231. }
  232. return $uploadedFiles;
  233. }
  234. }