Controller.php 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643
  1. <?php
  2. namespace Muzich\CoreBundle\lib;
  3. use Symfony\Bundle\FrameworkBundle\Controller\Controller as BaseController;
  4. use Muzich\CoreBundle\Searcher\ElementSearcher;
  5. use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
  6. use Muzich\CoreBundle\Form\Search\ElementSearchForm;
  7. use Muzich\CoreBundle\Form\Element\ElementAddForm;
  8. use Symfony\Component\HttpFoundation\Response;
  9. use Muzich\CoreBundle\Searcher\GlobalSearcher;
  10. use Muzich\CoreBundle\Entity\Element;
  11. use Muzich\CoreBundle\Entity\Presubscription;
  12. use Muzich\CoreBundle\Entity\User;
  13. use Muzich\CoreBundle\Security\Context as SecurityContext;
  14. class Controller extends BaseController
  15. {
  16. protected static $user = null;
  17. protected static $user_personal_query = null;
  18. protected static $tags = array();
  19. /** @var SecurityContext */
  20. protected $security_context;
  21. /**
  22. * Authenticate a user with Symfony Security
  23. *
  24. */
  25. protected function authenticateUser($user)
  26. {
  27. $providerKey = $this->container->getParameter('fos_user.firewall_name');
  28. $token = new UsernamePasswordToken($user, null, $providerKey, $user->getRoles());
  29. $this->container->get('security.context')->setToken($token);
  30. }
  31. /**
  32. * Met a jour les parametres de ElementSearcher pour la "mémoire" de la
  33. * recherche
  34. *
  35. * @param array $params
  36. */
  37. protected function setElementSearcherParams($params, $session_id = '')
  38. {
  39. if ($session_id != '')
  40. {
  41. $session_id = '.'.$session_id;
  42. }
  43. $this->get("session")->set('user.element_search.params'.$session_id, $params);
  44. }
  45. protected function isVisitor()
  46. {
  47. $user = $this->getUser();
  48. if ($user === 'anon.')
  49. {
  50. return true;
  51. }
  52. elseif ($user instanceof User)
  53. {
  54. return true;
  55. }
  56. throw new \Exception('Unable to determine user type');
  57. }
  58. /**
  59. * Retourn l'objet ElementSearcher en cours.
  60. *
  61. * @param int $count Si renseigné impact le nombre d'éléments qui seront
  62. * récupérés
  63. * @param boolean $force_new Si a vrai la méthode procéède comme si on
  64. * demandé un nouveau objet de recherche (basé sur les tags favoris donc).
  65. *
  66. * @return ElementSearcher
  67. */
  68. protected function getElementSearcher($count = null, $force_new = false, $session_id = '')
  69. {
  70. $session = $this->get("session");
  71. if ($session_id != '')
  72. {
  73. $session_id = '.'.$session_id;
  74. }
  75. // Si l'objet n'existe pas encore, a t-on déjà des paramètres de recherche
  76. if (!$session->has('user.element_search.params'.$session_id) || $force_new)
  77. {
  78. // Il nous faut instancier notre premier objet recherche
  79. // Premièrement on récupère les tags favoris de l'utilisateur
  80. $this->ElementSearcher = new ElementSearcher();
  81. $this->ElementSearcher->init(array(
  82. 'tags' => $this->getUserFavoriteTags(),
  83. 'count' => ($count)?$count:$this->container->getParameter('search_default_count')
  84. ));
  85. // Et on met en session les paramètres
  86. $session->set('user.element_search.params', $this->ElementSearcher->getParams());
  87. }
  88. else
  89. {
  90. // Des paramètres existes, on fabrique l'objet recherche
  91. $this->ElementSearcher = new ElementSearcher();
  92. // et on l'initatialise avec ces paramétres connus
  93. $this->ElementSearcher->init($session->get('user.element_search.params'.$session_id));
  94. if ($count)
  95. {
  96. $this->ElementSearcher->update(array('count' => $count));
  97. }
  98. }
  99. // on le retourne
  100. return $this->ElementSearcher;
  101. }
  102. protected function getUserFavoriteTags()
  103. {
  104. if (!$this->isVisitor())
  105. {
  106. return $this->getDoctrine()->getRepository('MuzichCoreBundle:User')
  107. ->getTagsFavorites(
  108. $this->getUserId(),
  109. $this->container->getParameter('search_default_favorites_tags_count')
  110. )
  111. ;
  112. }
  113. return array();
  114. }
  115. protected function getNewElementSearcher()
  116. {
  117. return $this->getElementSearcher(null, true);
  118. }
  119. /**
  120. * Retourne l'objet User. Il est possible de préciser de quel manière récupérer
  121. * l'utilisateur:
  122. *
  123. * $user = $this->getUser(true, array('join' => array(
  124. * 'groups_owned'
  125. * )));
  126. *
  127. * ou de forcer sa (re)récupération en base (sinon c'est l'objet static qui est renvoyé)
  128. *
  129. * @param boolean $personal_query
  130. * @param array $params
  131. * @param boolean $force_refresh
  132. * @return \Muzich\CoreBundle\Entity\User
  133. */
  134. public function getUser($personal_query = false, $params = array(), $force_refresh = false)
  135. {
  136. if (!$personal_query)
  137. {
  138. // Si on demande l'utilisateur sans forcer la réactualisation et que l'utilisateur
  139. // a déjà été demandé mais avec un requête personelle, on retourne cet utilisateur
  140. if (!$force_refresh && self::$user_personal_query)
  141. {
  142. return self::$user_personal_query;
  143. }
  144. // Si on demande une actualisation ou que l'utilisateur n'a pas encore été demandé
  145. // on va le récupérer
  146. else if ($force_refresh || !self::$user)
  147. {
  148. self::$user = $this->container->get('security.context')->getToken()->getUser();
  149. return self::$user;
  150. }
  151. return self::$user;
  152. }
  153. else
  154. {
  155. // Si l'on demande une réactualisation ou si l'user n'a pas encore été demandé
  156. // on va le récupérer en base.
  157. if ($force_refresh || !self::$user_personal_query)
  158. {
  159. $user = $this->container->get('security.context')->getToken()->getUser();
  160. if ($user !== 'anon.')
  161. {
  162. self::$user_personal_query = $this->getDoctrine()->getRepository('MuzichCoreBundle:User')->findOneById(
  163. $this->container->get('security.context')->getToken()->getUser()->getId(),
  164. array_key_exists('join', $params) ? $params['join'] : array()
  165. )->getSingleResult();
  166. return self::$user_personal_query;
  167. }
  168. else
  169. {
  170. return 'anon.';
  171. }
  172. }
  173. return self::$user_personal_query;
  174. }
  175. }
  176. /**
  177. * Retourne l'id de l'utilisateur en cours
  178. */
  179. protected function getUserId($return_null_if_visitor = false)
  180. {
  181. /**
  182. * Bug lors des tests: L'user n'est pas 'lié' a celui en base par doctrine.
  183. * Docrine le voit si on faire une requete directe.
  184. */
  185. if ($this->container->getParameter('env') == 'test')
  186. {
  187. $user_context = $this->container->get('security.context')->getToken()->getUser();
  188. if ($user_context !== 'anon.')
  189. {
  190. $user = $this->getDoctrine()->getRepository('MuzichCoreBundle:User')->findOneById(
  191. $user_context,
  192. array()
  193. )->getSingleResult();
  194. }
  195. }
  196. else
  197. {
  198. $user = $this->getUser();
  199. }
  200. if ($user !== 'anon.')
  201. {
  202. return $user->getId();
  203. }
  204. if ($return_null_if_visitor)
  205. {
  206. return null;
  207. }
  208. throw new \Exception('User not connected');
  209. }
  210. /**
  211. * Retourne un tabeau avec les tags connus.
  212. * TODO: Voir pour que cette info soit stocké (par exemple) dans un champs
  213. * texte en base. (json array)
  214. * TODO2: Voir si la question d'opt. "Formulaire d'ajout d'un élément" ne résoue pas
  215. * le problème du TODO ci-dessus.
  216. *
  217. * @return array
  218. */
  219. protected function getTagsArray($force_refresh = false)
  220. {
  221. throw new \Exception("Cette méthode ne doit plus être utilisé.");
  222. if (!count(self::$tags) || $force_refresh)
  223. {
  224. return self::$tags = $this->getDoctrine()->getRepository('MuzichCoreBundle:Tag')->getTagsArray();
  225. }
  226. return self::$tags;
  227. }
  228. /**
  229. * Retourne un tabeau avec les groupes accessible pour un ajout d'element.
  230. *
  231. * @return array
  232. */
  233. protected function getGroupsArray()
  234. {
  235. return $this->getDoctrine()->getRepository('MuzichCoreBundle:Group')
  236. ->getPublicAndOwnedArray($this->getUserId());
  237. }
  238. /**
  239. * Met en place un message de type flash.
  240. *
  241. * @param string $type
  242. * @param string $value
  243. */
  244. protected function setFlash($type, $value)
  245. {
  246. $this->container->get('session')->setFlash($type, $value);
  247. }
  248. /**
  249. * Instancie et retourne un objet ElementSearch
  250. *
  251. * @param array $params
  252. * @return ElementSearcher
  253. */
  254. protected function createSearchObject($params)
  255. {
  256. $search_object = new ElementSearcher();
  257. $search_object->init($params);
  258. return $search_object;
  259. }
  260. /**
  261. * Retourne un User en fonction du slug passé
  262. *
  263. * @param string $slug
  264. * @return User
  265. */
  266. protected function findUserWithSlug($slug)
  267. {
  268. try {
  269. return $this->getDoctrine()
  270. ->getRepository('MuzichCoreBundle:User')
  271. ->findOneBySlug($slug)
  272. ->getSingleResult()
  273. ;
  274. } catch (\Doctrine\ORM\NoResultException $e) {
  275. throw $this->createNotFoundException('Utilisateur introuvable.');
  276. }
  277. }
  278. /**
  279. * Retourne un Group en fonction du slug passé
  280. *
  281. * @param string $slug
  282. * @return Group
  283. */
  284. protected function findGroupWithSlug($slug)
  285. {
  286. try {
  287. return $this->getDoctrine()
  288. ->getRepository('MuzichCoreBundle:Group')
  289. ->findOneBySlug($slug)
  290. ->getSingleResult()
  291. ;
  292. } catch (\Doctrine\ORM\NoResultException $e) {
  293. throw $this->createNotFoundException('Groupe introuvable.');
  294. }
  295. }
  296. /**
  297. * Retourne un Group en fonction du id passé
  298. *
  299. * @param string $slug
  300. * @return Group
  301. */
  302. protected function findGroupWithId($id)
  303. {
  304. try {
  305. return $this->getDoctrine()
  306. ->getRepository('MuzichCoreBundle:Group')
  307. ->findOneById($id)
  308. ;
  309. } catch (\Doctrine\ORM\NoResultException $e) {
  310. throw $this->createNotFoundException('Groupe introuvable.');
  311. }
  312. }
  313. /**
  314. * Retourne le formulaire de recherche
  315. *
  316. * @param \Muzich\CoreBundle\Searcher\Searcher $search_object
  317. * @return \Symfony\Component\Form\Form
  318. */
  319. protected function getSearchForm($search_object)
  320. {
  321. return $this->createForm(
  322. new ElementSearchForm(),
  323. $search_object->getParams(true),
  324. array()
  325. );
  326. }
  327. /**
  328. * Retourne l'objet Form du formulaire de recherche global.
  329. *
  330. * @return \Symfony\Component\Form\Form
  331. */
  332. protected function getGlobalSearchForm($searcher = null)
  333. {
  334. if ($searcher === null)
  335. {
  336. $searcher = new GlobalSearcher();
  337. }
  338. return $this->createFormBuilder($searcher)
  339. ->add('string', 'text')
  340. ->getForm();
  341. }
  342. /**
  343. * Retourne le formulaire d'ajout d'élément
  344. *
  345. * @param \Muzich\CoreBundle\Searcher\Searcher $search_object
  346. * @return \Symfony\Component\Form\Form
  347. */
  348. protected function getAddForm($element = array(), $name = null)
  349. {
  350. //$form = new ElementAddForm();
  351. //$form->setName($name);
  352. //return $this->createForm(
  353. // $form,
  354. // $element,
  355. // array()
  356. //);
  357. $form = new ElementAddForm();
  358. $form->setName($name);
  359. return $this->createForm($form, $element);
  360. }
  361. /**
  362. * Retourne une réponse contenant et de type json
  363. *
  364. * @param array $content
  365. * @return Response
  366. */
  367. protected function jsonResponse($content)
  368. {
  369. $response = new Response(json_encode($content));
  370. $response->headers->set('Content-Type', 'application/json; charset=utf-8');
  371. return $response;
  372. }
  373. protected function jsonResponseError($error_type, $error_content = array())
  374. {
  375. return $this->jsonResponse(array(
  376. 'status' => 'error',
  377. 'error' => $error_type,
  378. 'data' => $error_content
  379. ));
  380. }
  381. protected function jsonNotFoundResponse()
  382. {
  383. $response = new Response(json_encode(array(
  384. 'status' => 'error',
  385. 'errors' => array('NotFound')
  386. )));
  387. $response->headers->set('Content-Type', 'application/json; charset=utf-8');
  388. return $response;
  389. }
  390. /**
  391. * Permet d'utiliser la méthode Assert que l'on utilise dans les templates
  392. * afin d'avoir une url correcte vers une ressource web (img, js, ...)
  393. *
  394. * @param string $path
  395. * @param string $packageName
  396. * @return string
  397. */
  398. protected function getAssetUrl($path, $packageName = null)
  399. {
  400. return $this->container->get('templating.helper.assets')->getUrl($path, $packageName);
  401. }
  402. /**
  403. * Retourne une traduction effectué par le translator
  404. *
  405. * @param string $string
  406. * @param array $params
  407. * @param string $package
  408. * @return string
  409. */
  410. protected function trans($string, $params = array(), $package = null)
  411. {
  412. return $this->get('translator')->trans($string, $params, $package);
  413. }
  414. /**
  415. * Permet de récupérer un objet réponse si l'utilisateur doit être connecté
  416. * pour accéder a cette ressource. On peux préciser $and_ajax pour que
  417. * la requete de type ajax soit une nécéssité.
  418. *
  419. * @return Response
  420. */
  421. protected function mustBeConnected($and_ajax = false)
  422. {
  423. if ($and_ajax && !$this->getRequest()->isXmlHttpRequest())
  424. {
  425. throw $this->createNotFoundException('Ressource ajax uniquement.');
  426. }
  427. if ($this->getUser() == 'anon.')
  428. {
  429. $this->setFlash('error', 'user.session_expired');
  430. if ($this->getRequest()->isXmlHttpRequest())
  431. {
  432. return $this->jsonResponse(array(
  433. 'status' => 'mustbeconnected'
  434. ));
  435. }
  436. else
  437. {
  438. return $this->redirect($this->generateUrl('index'));
  439. }
  440. }
  441. }
  442. /**
  443. *
  444. * @return \Doctrine\ORM\EntityManager
  445. */
  446. public function getEntityManager()
  447. {
  448. return $this->getDoctrine()->getEntityManager();
  449. }
  450. /**
  451. *
  452. * @param object $entity
  453. */
  454. public function persist($entity)
  455. {
  456. $this->getEntityManager()->persist($entity);
  457. }
  458. /**
  459. *
  460. * @param object $entity
  461. */
  462. public function remove($entity)
  463. {
  464. $this->getEntityManager()->remove($entity);
  465. }
  466. /**
  467. *
  468. */
  469. public function flush()
  470. {
  471. $this->getEntityManager()->flush();
  472. }
  473. /**
  474. * Cette méthode vérifie si l'élément qui vient d'être envoyé pourrais être
  475. * associé a un groupe de l'utilisateur.
  476. *
  477. * @param Element $element
  478. * @return array
  479. */
  480. protected function isAddedElementCanBeInGroup(Element $element)
  481. {
  482. $element_tags = $element->getTags();
  483. $groups = array();
  484. if ($element_tags)
  485. {
  486. foreach ($this->getUser()->getGroupsOwned() as $group)
  487. {
  488. foreach ($element_tags as $element_tag)
  489. {
  490. if ($group->hasThisTag($element_tag->getId()))
  491. {
  492. $groups[] = array(
  493. 'name' => $group->getName(),
  494. 'id' => $group->getId(),
  495. 'url' => $this->generateUrl('ajax_set_element_group', array(
  496. 'token' => $this->getUser()->getPersonalHash($element->getId()),
  497. 'element_id' => $element->getId(),
  498. 'group_id' => $group->getId()
  499. ))
  500. );
  501. }
  502. }
  503. }
  504. }
  505. return $groups;
  506. }
  507. protected function getPreSubscriptionForm()
  508. {
  509. return $this->createFormBuilder(new Presubscription())
  510. ->add('email', 'email')
  511. ->getForm()
  512. ;
  513. }
  514. protected function getDisplayAutoplayBooleanForContext($context)
  515. {
  516. if (in_array($context,
  517. $this->container->getParameter('autoplay_contexts')
  518. ))
  519. {
  520. return true;
  521. }
  522. return false;
  523. }
  524. protected function sendEmailconfirmationEmail($set_send_time = true)
  525. {
  526. $user = $this->getUser();
  527. $tokenGenerator = $this->container->get('fos_user.util.token_generator');
  528. $user->setConfirmationToken($tokenGenerator->generateToken());
  529. if ($set_send_time)
  530. $user->setEmailConfirmationSentTimestamp(time());
  531. $token = hash('sha256', $user->getConfirmationToken().$user->getEmail());
  532. $url = $this->get('router')->generate('email_confirm', array('token' => $token), true);
  533. $rendered = $this->get('templating')->render('MuzichUserBundle:User:confirm_email_email.txt.twig', array(
  534. 'confirmation_url' => $url
  535. ));
  536. //$this->sendEmailMessage($rendered, $this->parameters['from_email']['resetting'], $user->getEmail());
  537. // Render the email, use the first line as the subject, and the rest as the body
  538. $renderedLines = explode("\n", trim($rendered));
  539. $subject = $renderedLines[0];
  540. $body = implode("\n", array_slice($renderedLines, 1));
  541. $message = \Swift_Message::newInstance()
  542. ->setSubject($subject)
  543. ->setFrom('contact@muzi.ch')
  544. ->setTo($user->getEmail())
  545. ->setBody($body);
  546. $message->getHeaders()->addTextHeader('List-Unsubscribe', 'unsubscribe@muzi.ch');
  547. $mailer = $this->get('mailer');
  548. $mailer->send($message);
  549. $this->persist($user);
  550. $this->flush();
  551. }
  552. protected function getParameter($key)
  553. {
  554. return $this->container->getParameter($key);
  555. }
  556. protected function userHaveNonConditionToMakeAction($action)
  557. {
  558. $secutity_context = $this->getSecurityContext();
  559. if (($condition = $secutity_context->actionIsAffectedBy(SecurityContext::AFFECT_CANT_MAKE, $action)) !== false)
  560. {
  561. return $condition;
  562. }
  563. return false;
  564. }
  565. /** @return SecurityContext */
  566. protected function getSecurityContext()
  567. {
  568. if ($this->security_context == null)
  569. $this->security_context = new SecurityContext($this->getUser());
  570. return $this->security_context;
  571. }
  572. }