UserController.php 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  1. <?php
  2. namespace Muzich\UserBundle\Controller;
  3. use Muzich\CoreBundle\lib\Controller;
  4. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  5. use Symfony\Component\HttpFoundation\RedirectResponse;
  6. use Symfony\Component\Security\Core\Exception\AccessDeniedException;
  7. use FOS\UserBundle\Model\UserInterface;
  8. use Muzich\CoreBundle\Form\Tag\TagFavoritesForm;
  9. use Symfony\Component\Validator\Constraints\Email;
  10. use Symfony\Component\Validator\Constraints\Collection;
  11. use Symfony\Component\HttpFoundation\Request;
  12. class UserController extends Controller
  13. {
  14. protected $tags_favorites = null;
  15. protected function getChangeEmailForm()
  16. {
  17. $collectionConstraint = new Collection(array(
  18. 'email' => new Email(array('message' => 'error.changeemail.email.invalid')),
  19. ));
  20. return $this->createFormBuilder(null, array(
  21. //'validation_constraint' => $collectionConstraint, UPGRADE 2.1
  22. 'constraints' => $collectionConstraint,
  23. ))
  24. ->add('email', 'text')
  25. ->getForm()
  26. ;
  27. }
  28. protected function getPreferencesForm()
  29. {
  30. /**
  31. * Bug lors des tests: L'user n'est pas 'lié' a celui en base par doctrine.
  32. * Docrine le voit si on faire une requete directe.
  33. */
  34. if ($this->container->getParameter('env') == 'test')
  35. {
  36. $user = $this->getDoctrine()->getRepository('MuzichCoreBundle:User')->findOneById(
  37. $this->container->get('security.context')->getToken()->getUser()->getId(),
  38. array()
  39. )->getSingleResult();
  40. }
  41. else
  42. {
  43. $user = $this->getUser();
  44. }
  45. return $this->createFormBuilder($user)
  46. ->add('mail_newsletter', 'checkbox', array('required' => false))
  47. ->add('mail_partner', 'checkbox', array('required' => false))
  48. ->getForm()
  49. ;
  50. }
  51. protected function getTagsFavoritesForm($user)
  52. {
  53. $ids = array();
  54. foreach ($this->getTagsFavorites() as $id => $name)
  55. {
  56. $ids[] = $id;
  57. }
  58. return $this->createForm(
  59. new TagFavoritesForm(),
  60. array('tags' => json_encode($ids))
  61. );
  62. }
  63. protected function getTagsFavorites($force = false)
  64. {
  65. if ($this->tags_favorites === null || $force)
  66. {
  67. $user = $this->getUser();
  68. /**
  69. * Bug lors des tests: L'user n'est pas 'lié' a celui en base par doctrine.
  70. * Docrine le voit si on faire une requete directe.
  71. */
  72. if ($this->container->getParameter('env') == 'test')
  73. {
  74. $user = $this->getDoctrine()->getRepository('MuzichCoreBundle:User')->findOneById(
  75. $this->container->get('security.context')->getToken()->getUser()->getId(),
  76. array()
  77. )->getSingleResult();
  78. }
  79. $this->tags_favorites = $this->getDoctrine()->getRepository('MuzichCoreBundle:User')
  80. ->getTagsFavorites($user->getId())
  81. ;
  82. }
  83. return $this->tags_favorites;
  84. }
  85. /**
  86. * Page de configuration de son compte
  87. *
  88. * @Template()
  89. */
  90. public function accountAction()
  91. {
  92. $user = $this->getUser();
  93. $form_password = $this->container->get('fos_user.change_password.form');
  94. $form_tags_favorites = $this->getTagsFavoritesForm($user);
  95. $change_email_form = $this->getChangeEmailForm();
  96. return array(
  97. 'user' => $user,
  98. 'form_password' => $form_password->createView(),
  99. 'form_tags_favorites' => $form_tags_favorites->createView(),
  100. 'form_tags_favorites_name' => $form_tags_favorites->getName(),
  101. 'favorite_tags_id' => $this->getTagsFavorites(),
  102. 'change_email_form' => $change_email_form->createView(),
  103. 'avatar_form' => $this->getAvatarForm()->createView(),
  104. 'preferences_form' => $this->getPreferencesForm()->createView()
  105. );
  106. }
  107. protected function getAvatarForm()
  108. {
  109. return $this->createFormBuilder($this->getUser())
  110. ->add('avatar')
  111. ->getForm()
  112. ;
  113. }
  114. /**
  115. * Un bug étrange empêche la mise ne place de contraintes sur le formulaire
  116. * d'inscription. On effectue alors les vérifications ici.
  117. *
  118. * C'est sale, mais ça marche ...
  119. *
  120. * @return array of string errors
  121. */
  122. protected function checkRegistrationInformations($form)
  123. {
  124. $errors = array();
  125. $form->bind($this->getRequest());
  126. $form_values = $this->getRequest()->request->get($form->getName());
  127. $user = $form->getData();
  128. /*
  129. * Contrôle de la taille du pseudo
  130. * min: 3
  131. * max: 32
  132. */
  133. if (strlen($user->getUsername()) < 3)
  134. {
  135. $errors[] = $this->get('translator')->trans(
  136. 'error.registration.username.min',
  137. array('%limit%' => 3),
  138. 'validators'
  139. );
  140. }
  141. if (strlen($user->getUsername()) > 32)
  142. {
  143. $errors[] = $this->get('translator')->trans(
  144. 'error.registration.username.max',
  145. array('%limit%' => 32),
  146. 'validators'
  147. );
  148. }
  149. /**
  150. * Mot de passes indentiques
  151. */
  152. if ($form_values['plainPassword']['first'] != $form_values['plainPassword']['second'])
  153. {
  154. $errors[] = $this->get('translator')->trans(
  155. 'error.registration.password.notsame',
  156. array(),
  157. 'validators'
  158. );
  159. }
  160. return $errors;
  161. }
  162. public function registerAction()
  163. {
  164. $form = $this->container->get('fos_user.registration.form');
  165. $formHandler = $this->container->get('fos_user.registration.form.handler');
  166. $confirmationEnabled = $this->container->getParameter('fos_user.registration.confirmation.enabled');
  167. $errors = array();
  168. // On contrôle le token en premier lieu
  169. $form_values = $this->getRequest()->request->get($form->getName());
  170. $r_token = $this->getDoctrine()->getRepository('MuzichCoreBundle:RegistrationToken')
  171. ->findOneBy(array('token' => $form_values["token"], 'used' => false))
  172. ;
  173. if ($r_token)
  174. {
  175. if (count(($errors = $this->checkRegistrationInformations($form))) < 1)
  176. {
  177. $process = $formHandler->process($confirmationEnabled);
  178. if ($process) {
  179. $user = $form->getData();
  180. if ($confirmationEnabled) {
  181. $this->container->get('session')->set('fos_user_send_confirmation_email/email', $user->getEmail());
  182. $route = 'fos_user_registration_check_email';
  183. } else {
  184. $this->authenticateUser($user);
  185. $route = 'start';
  186. }
  187. $this->setFlash('fos_user_success', 'registration.flash.user_created');
  188. $url = $this->generateUrl($route);
  189. $r_token->addUseCount();
  190. $em = $this->getDoctrine()->getEntityManager();
  191. $em->persist($r_token);
  192. $em->flush();
  193. return new RedirectResponse($url);
  194. }
  195. }
  196. }
  197. else
  198. {
  199. $form->bind($this->getRequest());
  200. $errors[] = $this->get('translator')->trans(
  201. 'registration.token.error',
  202. array(),
  203. 'validators'
  204. );
  205. }
  206. return $this->container->get('templating')->renderResponse(
  207. 'MuzichIndexBundle:Index:index.html.twig',
  208. array(
  209. 'form' => $form->createView(),
  210. 'error' => null,
  211. 'registration_errors' => $form->getErrors(),
  212. 'registration_errors_pers' => $errors,
  213. 'last_username' => null,
  214. 'registration_page' => true,
  215. 'presubscription_form' => $this->getPreSubscriptionForm()->createView()
  216. )
  217. );
  218. }
  219. /**
  220. * Un bug étrange empêche la mise ne place de contraintes sur le formulaire
  221. * d'inscription. On effectue alors les vérifications ici.
  222. *
  223. * C'est sale, mais ça marche ...
  224. *
  225. * @return array of string errors
  226. */
  227. protected function checkChangePasswordInformations($form)
  228. {
  229. $errors = array();
  230. $form_values = $this->getRequest()->request->get($form->getName());
  231. $user = $form->getData();
  232. /**
  233. * Mot de passes indentiques
  234. */
  235. if ($form_values['new']['first'] != $form_values['new']['second'])
  236. {
  237. $errors[] = $this->get('translator')->trans(
  238. 'error.changepassword.new.notsame',
  239. array(),
  240. 'validators'
  241. );
  242. }
  243. return $errors;
  244. }
  245. public function changePasswordAction()
  246. {
  247. $user = $this->getUser();
  248. /**
  249. * Bug lors des tests: L'user n'est pas 'lié' a celui en base par doctrine.
  250. * Docrine le voit si on faire une requete directe.
  251. */
  252. if ($this->container->getParameter('env') == 'test')
  253. {
  254. $user = $this->getDoctrine()->getRepository('MuzichCoreBundle:User')->findOneById(
  255. $this->container->get('security.context')->getToken()->getUser()->getId(),
  256. array()
  257. )->getSingleResult();
  258. }
  259. if (!is_object($user) || !$user instanceof UserInterface) {
  260. throw new AccessDeniedException('This user does not have access to this section.');
  261. }
  262. $form = $this->container->get('fos_user.change_password.form');
  263. $formHandler = $this->container->get('fos_user.change_password.form.handler');
  264. $process = $formHandler->process($user);
  265. if (count(($errors = $this->checkChangePasswordInformations($form))) < 1 && $process)
  266. {
  267. $this->container->get('session')->setFlash('fos_user_success', 'change_password.flash.success');
  268. return new RedirectResponse($this->generateUrl('my_account'));
  269. }
  270. else
  271. {
  272. $form_tags_favorites = $this->getTagsFavoritesForm($user);
  273. $change_email_form = $this->getChangeEmailForm();
  274. return $this->container->get('templating')->renderResponse(
  275. 'MuzichUserBundle:User:account.html.twig',
  276. array(
  277. 'form_password' => $form->createView(),
  278. 'errors_pers' => $errors,
  279. 'user' => $user,
  280. 'form_tags_favorites' => $form_tags_favorites->createView(),
  281. 'form_tags_favorites_name' => $form_tags_favorites->getName(),
  282. 'favorite_tags_id' => $this->getTagsFavorites(),
  283. 'change_email_form' => $change_email_form->createView(),
  284. 'avatar_form' => $this->getAvatarForm()->createView()
  285. )
  286. );
  287. }
  288. }
  289. /**
  290. * Page ouverte après l'inscription sur laquelle on propose de saisir ses
  291. * tags favoris.
  292. *
  293. * @Template()
  294. */
  295. public function startAction()
  296. {
  297. $user = $this->getUser();
  298. $form_tags_favorites = $this->getTagsFavoritesForm($user);
  299. return array(
  300. 'favorite_tags_id' => $this->getTagsFavorites(),
  301. 'form_tags_favorites' => $form_tags_favorites->createView(),
  302. 'form_tags_favorites_name' => $form_tags_favorites->getName(),
  303. );
  304. }
  305. /**
  306. *
  307. * @param string $redirect
  308. */
  309. public function updateTagFavoritesAction($redirect)
  310. {
  311. $request = $this->getRequest();
  312. $user = $this->getUser(true, array('join' => array('favorites_tags')));
  313. /**
  314. * Bug lors des tests: L'user n'est pas 'lié' a celui en base par doctrine.
  315. * Docrine le voit si on faire une requete directe.
  316. */
  317. if ($this->container->getParameter('env') == 'test')
  318. {
  319. $user = $this->getDoctrine()->getRepository('MuzichCoreBundle:User')->findOneById(
  320. $this->container->get('security.context')->getToken()->getUser()->getId(),
  321. array()
  322. )->getSingleResult();
  323. }
  324. $form = $this->getTagsFavoritesForm($user);
  325. if ($request->getMethod() == 'POST')
  326. {
  327. $form->bind($request);
  328. if ($form->isValid())
  329. {
  330. $data = $form->getData();
  331. $user->updateTagsFavoritesById($this->getDoctrine()->getEntityManager(), $data['tags']);
  332. // On réinitialise l'eventuel session de recherche en mémoire
  333. $session = $this->get("session");
  334. $session->remove('user.element_search.params');
  335. $this->container->get('session')->setFlash('success', 'Vos tags péférés ont correctements été mis a jour.');
  336. }
  337. else
  338. {
  339. return $this->container->get('templating')->renderResponse(
  340. 'MuzichUserBundle:User:start.html.twig',
  341. array(
  342. 'form' => $form->createView()
  343. )
  344. );
  345. }
  346. }
  347. // (Il y aura aussi une redirection vers "mon compte / tags")
  348. if ($redirect == 'home')
  349. {
  350. return $this->redirect($this->generateUrl('home'));
  351. }
  352. else
  353. {
  354. return $this->redirect($this->generateUrl('my_account'));
  355. }
  356. }
  357. protected function checkChangeEmailFrequencies($user, $new_email)
  358. {
  359. $delay = $this->container->getParameter('changeemail_security_delay');
  360. if (($last_request_datetime = $user->getEmailRequestedDatetime()))
  361. {
  362. if ((time() - $last_request_datetime) < $delay)
  363. {
  364. return false;
  365. }
  366. }
  367. return true;
  368. }
  369. /**
  370. * Procédure de demande de changement de mot de passe
  371. */
  372. public function changeEmailRequestAction()
  373. {
  374. $em = $this->getDoctrine()->getEntityManager();
  375. $user = $this->getUser();
  376. /**
  377. * Bug lors des tests: L'user n'est pas 'lié' a celui en base par doctrine.
  378. * Docrine le voit si on faire une requete directe.
  379. */
  380. if ($this->container->getParameter('env') == 'test')
  381. {
  382. $user = $this->getDoctrine()->getRepository('MuzichCoreBundle:User')->findOneById(
  383. $this->container->get('security.context')->getToken()->getUser()->getId(),
  384. array()
  385. )->getSingleResult();
  386. }
  387. $request = $this->getRequest();
  388. $change_email_form = $this->getChangeEmailForm();
  389. $change_email_form->bind($request);
  390. if ($change_email_form->isValid())
  391. {
  392. $data = $change_email_form->getData();
  393. $email = $data['email'];
  394. if (!$this->checkChangeEmailFrequencies($user, $email))
  395. {
  396. $this->setFlash('error', 'user.changeemail.wait');
  397. return new RedirectResponse($this->generateUrl('my_account'));
  398. }
  399. /*
  400. * Optimisation: Ecrire une lib Mailer pour gérer les envois.
  401. * cf le mailer de FOSUserBundle
  402. */
  403. // On renseigne en base l'email demandé
  404. $user->setEmailRequested($email);
  405. $user->setEmailRequestedDatetime(time());
  406. //$user->generateConfirmationToken(); UPGRADE FOSUserBundle 1.3
  407. $tokenGenerator = $this->container->get('fos_user.util.token_generator');
  408. $user->setConfirmationToken($tokenGenerator->generateToken());
  409. $token = hash('sha256', $user->getConfirmationToken().$email);
  410. $url = $this->get('router')->generate('change_email_confirm', array('token' => $token), true);
  411. $rendered = $this->get('templating')->render('MuzichUserBundle:User:change_email_mail.txt.twig', array(
  412. 'user' => $user,
  413. 'confirmationUrl' => $url
  414. ));
  415. //$this->sendEmailMessage($rendered, $this->parameters['from_email']['resetting'], $user->getEmail());
  416. // Render the email, use the first line as the subject, and the rest as the body
  417. $renderedLines = explode("\n", trim($rendered));
  418. $subject = $renderedLines[0];
  419. $body = implode("\n", array_slice($renderedLines, 1));
  420. $message = \Swift_Message::newInstance()
  421. ->setSubject($subject)
  422. ->setFrom('noreply@muzi.ch')
  423. ->setTo($email)
  424. ->setBody($body);
  425. $mailer = $this->get('mailer');
  426. $mailer->send($message);
  427. $this->setFlash('success', 'user.changeemail.mail_send');
  428. $em->flush();
  429. return new RedirectResponse($this->generateUrl('my_account'));
  430. }
  431. // En cas d'échec
  432. $form_password = $this->container->get('fos_user.change_password.form');
  433. $form_tags_favorites = $this->getTagsFavoritesForm($user);
  434. return $this->container->get('templating')->renderResponse(
  435. 'MuzichUserBundle:User:account.html.twig',
  436. array(
  437. 'user' => $user,
  438. 'form_password' => $form_password->createView(),
  439. 'form_tags_favorites' => $form_tags_favorites->createView(),
  440. 'form_tags_favorites_name' => $form_tags_favorites->getName(),
  441. 'favorite_tags_id' => $this->getTagsFavorites(),
  442. 'change_email_form' => $change_email_form->createView(),
  443. 'avatar_form' => $this->getAvatarForm()->createView()
  444. )
  445. );
  446. }
  447. /**
  448. * Procédure de confirmation de la nouvelle adresse email.
  449. */
  450. public function changeEmailConfirmAction($token)
  451. {
  452. $em = $this->getDoctrine()->getEntityManager();
  453. $um = $this->get('muzich_user_manager');
  454. $user = $this->getUser();
  455. /**
  456. * Bug lors des tests: L'user n'est pas 'lié' a celui en base par doctrine.
  457. * Docrine le voit si on faire une requete directe.
  458. */
  459. if ($this->container->getParameter('env') == 'test')
  460. {
  461. $user = $this->getDoctrine()->getRepository('MuzichCoreBundle:User')->findOneById(
  462. $this->container->get('security.context')->getToken()->getUser()->getId(),
  463. array()
  464. )->getSingleResult();
  465. }
  466. $token_ = hash('sha256', $user->getConfirmationToken().($email = $user->getEmailRequested()));
  467. // Le token est-il valide
  468. if ($token_ != $token)
  469. {
  470. $this->setFlash('error', 'user.changeemail.token_invalid');
  471. return new RedirectResponse($this->generateUrl('my_account'));
  472. }
  473. $user->setEmail($email);
  474. $user->setEmailRequested(null);
  475. $um->updateCanonicalFields($user);
  476. $em->flush();
  477. $this->setFlash('success', 'user.changeemail.success');
  478. return new RedirectResponse($this->generateUrl('my_account'));
  479. }
  480. /**
  481. *
  482. * @param string $town
  483. * @param string $country
  484. * @param string $token
  485. * @return Response
  486. */
  487. public function updateAddressAction($token)
  488. {
  489. if (($response = $this->mustBeConnected(true)))
  490. {
  491. return $response;
  492. }
  493. /**
  494. * Bug lors des tests: L'user n'est pas 'lié' a celui en base par doctrine.
  495. * Docrine le voit si on faire une requete directe.
  496. */
  497. $user = $this->getUser();
  498. if ($this->container->getParameter('env') == 'test')
  499. {
  500. $user = $this->getDoctrine()->getRepository('MuzichCoreBundle:User')->findOneById(
  501. $this->container->get('security.context')->getToken()->getUser()->getId(),
  502. array()
  503. )->getSingleResult();
  504. }
  505. $errors = array();
  506. if ($user->getPersonalHash() != $token)
  507. {
  508. $errors[] = 'NotAllowed';
  509. }
  510. if (!trim($this->getRequest()->request->get('town')))
  511. {
  512. $errors[] = $this->trans('my_account.address.form.errors.notown', array(), 'userui');
  513. }
  514. if (!trim($this->getRequest()->request->get('country')))
  515. {
  516. $errors[] = $this->trans('my_account.address.form.errors.nocountry', array(), 'userui');
  517. }
  518. if (count($errors))
  519. {
  520. return $this->jsonResponse(array(
  521. 'status' => 'error',
  522. 'errors' => $errors
  523. ));
  524. }
  525. $user->setTown(trim($this->getRequest()->request->get('town')));
  526. $user->setCountry(trim($this->getRequest()->request->get('country')));
  527. $this->getDoctrine()->getEntityManager()->persist($user);
  528. $this->getDoctrine()->getEntityManager()->flush();
  529. return $this->jsonResponse(array(
  530. 'status' => 'success'
  531. ));
  532. }
  533. public function updateAvatarAction(Request $request)
  534. {
  535. $form = $this->getAvatarForm();
  536. $form->bind($request);
  537. if ($form->isValid()) {
  538. $em = $this->getEntityManager();
  539. $form->getData()->preUploadAvatar();
  540. $form->getData()->uploadAvatar();
  541. $em->persist($form->getData());
  542. $em->flush();
  543. $this->setFlash('success',
  544. $this->trans('my_account.avatar.success', array(), 'userui'));
  545. return $this->redirect($this->generateUrl('my_account'));
  546. }
  547. $this->setFlash('error',
  548. $this->trans('my_account.avatar.error', array(), 'userui'));
  549. return $this->redirect($this->generateUrl('my_account'));
  550. }
  551. public function updatePreferencesAction(Request $request)
  552. {
  553. $form = $this->getPreferencesForm();
  554. $form->bind($request);
  555. if ($form->isValid()) {
  556. $em = $this->getEntityManager();
  557. $em->persist($form->getData());
  558. $em->flush();
  559. $this->setFlash('success',
  560. $this->trans('my_account.preferences.success', array(), 'userui'));
  561. return $this->redirect($this->generateUrl('my_account'));
  562. }
  563. $this->setFlash('error',
  564. $this->trans('my_account.preferences.error', array(), 'userui'));
  565. return $this->redirect($this->generateUrl('my_account'));
  566. }
  567. }