CoreController.php 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637
  1. <?php
  2. namespace Muzich\CoreBundle\Controller;
  3. use Muzich\CoreBundle\lib\Controller;
  4. //use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  5. use Muzich\CoreBundle\Entity\FollowUser;
  6. use Muzich\CoreBundle\Entity\FollowGroup;
  7. //use Doctrine\ORM\Query;
  8. use Muzich\CoreBundle\Form\Element\ElementAddForm;
  9. use Muzich\CoreBundle\ElementFactory\ElementManager;
  10. use Muzich\CoreBundle\Entity\Element;
  11. use Symfony\Component\HttpFoundation\RedirectResponse;
  12. use Muzich\CoreBundle\Form\Search\ElementSearchForm;
  13. use Symfony\Component\Routing\Exception\ResourceNotFoundException;
  14. use Muzich\CoreBundle\Entity\Tag;
  15. use Muzich\CoreBundle\Managers\TagManager;
  16. use Muzich\CoreBundle\Entity\UsersTagsFavorites;
  17. use Muzich\CoreBundle\Managers\ElementReportManager;
  18. use Muzich\CoreBundle\Propagator\EventUser;
  19. class CoreController extends Controller
  20. {
  21. /**
  22. * Action permettant de changer le language
  23. *
  24. * @param string $language
  25. * @return RedirectResponse
  26. */
  27. public function changeLanguageAction($language)
  28. {
  29. if($language != null)
  30. {
  31. $old = $this->get('session')->getLocale();
  32. $this->get('session')->setLocale($language);
  33. }
  34. $url_referer = $this->container->get('request')->headers->get('referer');
  35. $url_referer = str_replace(
  36. $siteurl = $this->container->getParameter('siteurl'),
  37. '',
  38. $url_referer
  39. );
  40. try {
  41. $params = $this->get('router')->match($url_referer);
  42. } catch (ResourceNotFoundException $exc) {
  43. return $this->redirect($this->generateUrl('home', array('_locale' => $language)));
  44. }
  45. $params['_locale'] = $language;
  46. $route = $params['_route'];
  47. unset($params['_route'], $params['_controller']);
  48. $new_url = $this->generateUrl($route, $params);
  49. return new RedirectResponse($new_url);
  50. }
  51. /**
  52. * Cette action permet a un utilisateur de suivre ou de ne plus suivre
  53. * un utilisateur ou un groupe.
  54. *
  55. * @param string $type
  56. * @param int $id
  57. * @param string $salt
  58. */
  59. public function followAction($type, $id, $token)
  60. {
  61. if (($response = $this->mustBeConnected()))
  62. {
  63. return $response;
  64. }
  65. $user = $this->getUser();
  66. /**
  67. * Bug lors des tests: L'user n'est pas 'lié' a celui en base par doctrine.
  68. * Docrine le voit si on faire une requete directe.
  69. */
  70. if ($this->container->getParameter('env') == 'test')
  71. {
  72. $user = $this->getDoctrine()->getRepository('MuzichCoreBundle:User')->findOneById(
  73. $this->container->get('security.context')->getToken()->getUser()->getId(),
  74. array()
  75. )->getSingleResult();
  76. }
  77. // Vérifications préléminaires
  78. if ($user->getPersonalHash() != $token
  79. || !in_array($type, array('user', 'group'))
  80. || !is_numeric($id)
  81. || $user->getId() == $id
  82. )
  83. {
  84. throw $this->createNotFoundException();
  85. }
  86. // On tente de récupérer l'enregistrement FollowUser / FollowGroup
  87. $em = $this->getDoctrine()->getEntityManager();
  88. $Follow = $em
  89. ->getRepository('MuzichCoreBundle:Follow' . ucfirst($type))
  90. ->findOneBy(
  91. array(
  92. 'follower' => $user->getId(),
  93. ($type == 'user') ? 'followed' : 'group' => $id
  94. )
  95. )
  96. ;
  97. // Si il existe déjà c'est qu'il ne veut plus suivre
  98. if ($Follow)
  99. {
  100. if ($type == 'user')
  101. {
  102. // L'utilisateur suis déjà, on doit détruire l'entité
  103. $event = new EventUser($this->container);
  104. $event->removeFromFollow($Follow->getFollowed());
  105. $em->persist($Follow->getFollowed());
  106. }
  107. $em->remove($Follow);
  108. $em->flush();
  109. $following = false;
  110. }
  111. // Sinon, c'est qu'il veut le suivre
  112. else
  113. {
  114. // On récupére l'entité a suivre
  115. $followed = $em->getRepository('MuzichCoreBundle:'.ucfirst($type))->find($id);
  116. if (!$followed) {
  117. throw $this->createNotFoundException('No '.$type.' found for id '.$id);
  118. }
  119. // On instancie te renseigne l'objet Follow****
  120. if ($type == 'user') { $Follow = new FollowUser(); }
  121. else { $Follow = new FollowGroup(); }
  122. $Follow->setFollower($user);
  123. if ($type == 'user')
  124. {
  125. $Follow->setFollowed($followed);
  126. $event = new EventUser($this->container);
  127. $event->addToFollow($followed, $this->getUser());
  128. $em->persist($followed);
  129. }
  130. else { $Follow->setGroup($followed); }
  131. $em->persist($Follow);
  132. $em->flush();
  133. $following = true;
  134. }
  135. if ($this->getRequest()->isXmlHttpRequest())
  136. {
  137. return $this->jsonResponse(array(
  138. 'status' => 'success',
  139. 'following' => $following
  140. ));
  141. }
  142. else
  143. {
  144. return $this->redirect($this->container->get('request')->headers->get('referer'));
  145. }
  146. }
  147. /**
  148. * Procédure d'ajout d'un element
  149. */
  150. public function elementAddAction($group_slug)
  151. {
  152. if (($response = $this->mustBeConnected()))
  153. {
  154. return $response;
  155. }
  156. if ($this->getRequest()->getMethod() != 'POST')
  157. {
  158. throw $this->createNotFoundException('Cette ressource n\'est pas accessible');
  159. }
  160. $user = $this->getUser(true, array('join' => array('groups_owned_groups_tags')));
  161. $em = $this->getDoctrine()->getEntityManager();
  162. /*
  163. * Contrôle préléminaire si groupe précisé
  164. */
  165. $group = null;
  166. if ($group_slug)
  167. {
  168. $group = $this->findGroupWithSlug($group_slug);
  169. if (!$group->userCanAddElement($this->getUserId()))
  170. {
  171. $group = null;
  172. throw $this->createNotFoundException('Vous ne pouvez pas ajouter d\'éléments a ce groupe');
  173. }
  174. }
  175. $element = new Element();
  176. $element->setType('none');
  177. $form = $this->getAddForm($element);
  178. $form->bindRequest($this->getRequest());
  179. if ($form->isValid())
  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 = $this->getDoctrine()->getRepository('MuzichCoreBundle:User')->findOneById(
  188. $this->container->get('security.context')->getToken()->getUser()->getId(),
  189. array()
  190. )->getSingleResult();
  191. }
  192. // On utilise le gestionnaire d'élément
  193. $factory = new ElementManager($element, $em, $this->container);
  194. $factory->proceedFill($user);
  195. // Si on a précisé un groupe dans lequel mettre l'element
  196. if ($group)
  197. {
  198. $element->setGroup($group);
  199. $redirect_url = $this->generateUrl('show_group', array('slug' => $group_slug));
  200. }
  201. else
  202. {
  203. $redirect_url = $this->generateUrl('home');
  204. }
  205. $em->persist($element);
  206. $em->flush();
  207. if ($this->getRequest()->isXmlHttpRequest())
  208. {
  209. // Récupération du li
  210. if (!$group)
  211. {
  212. $html = $this->render('MuzichCoreBundle:SearchElement:li.element.html.twig', array(
  213. 'element' => $element,
  214. 'class_color' => 'odd'
  215. ))->getContent();
  216. }
  217. else
  218. {
  219. $html = $this->render('MuzichCoreBundle:SearchElement:li.element.html.twig', array(
  220. 'element' => $element,
  221. 'class_color' => 'odd',
  222. 'no_group_name' => true
  223. ))->getContent();
  224. }
  225. return $this->jsonResponse(array(
  226. 'status' => 'success',
  227. 'html' => $html,
  228. 'groups' => (!$group)?$this->isAddedElementCanBeInGroup($element):array()
  229. ));
  230. }
  231. else
  232. {
  233. return $this->redirect($redirect_url);
  234. }
  235. }
  236. else
  237. {
  238. if ($this->getRequest()->isXmlHttpRequest())
  239. {
  240. // Récupération des erreurs
  241. $validator = $this->container->get('validator');
  242. $errorList = $validator->validate($form);
  243. $errors = array();
  244. foreach ($errorList as $error)
  245. {
  246. $errors[] = $this->trans($error->getMessage(), array(), 'validators');
  247. }
  248. foreach ($form->getErrors() as $error)
  249. {
  250. if (!in_array($err = $this->trans($error->getMessageTemplate(), array(), 'validators'), $errors))
  251. {
  252. $errors[] = $err;
  253. }
  254. }
  255. return $this->jsonResponse(array(
  256. 'status' => 'error',
  257. 'errors' => $errors
  258. ));
  259. }
  260. else
  261. {
  262. if (!$group_slug)
  263. {
  264. $search_object = $this->getElementSearcher();
  265. $search_form = $this->getSearchForm($search_object);
  266. $add_form = $form;
  267. return $this->render('MuzichHomeBundle:Home:index.html.twig', array(
  268. 'search_tags_id' => $search_object->getTags(),
  269. 'user' => $this->getUser(),
  270. 'add_form' => $add_form->createView(),
  271. 'add_form_name' => 'add',
  272. 'search_form' => $search_form->createView(),
  273. 'search_form_name' => 'search',
  274. 'network_public' => $search_object->isNetworkPublic(),
  275. 'elements' => $search_object->getElements($this->getDoctrine(), $this->getUserId()),
  276. 'more_count' => $this->container->getParameter('search_default_count')*2,
  277. 'ids_display' => $search_object->getIdsDisplay()
  278. ));
  279. }
  280. else
  281. {
  282. $group = $this->findGroupWithSlug($group_slug);
  283. $search_object = $this->createSearchObject(array(
  284. 'group_id' => $group->getId()
  285. ));
  286. ($group->getOwner()->getId() == $this->getUserId()) ? $his = true : $his = false;
  287. if ($his || $group->getOpen())
  288. {
  289. $add_form = $form;
  290. }
  291. return $this->render('MuzichHomeBundle:Show:showGroup.html.twig', array(
  292. 'group' => $group,
  293. 'his_group' => ($group->getOwner()->getId() == $this->getUserId()) ? true : false,
  294. 'elements' => $search_object->getElements($this->getDoctrine(), $this->getUserId()),
  295. 'following' => $this->getUser()->isFollowingGroupByQuery($this->getDoctrine(), $group->getId()),
  296. 'user' => $this->getUser(),
  297. 'add_form' => (isset($add_form)) ? $add_form->createView() : null,
  298. 'add_form_name' => (isset($add_form)) ? 'add' : null,
  299. 'more_count' => null,
  300. 'more_route' => 'show_group_more',
  301. 'ids_display' => $search_object->getIdsDisplay()
  302. ));
  303. }
  304. }
  305. }
  306. }
  307. /**
  308. * Cette méthode vérifie si l'élément qui vient d'être envoyé pourrais être
  309. * associé a un groupe de l'utilisateur.
  310. *
  311. * @param Element $element
  312. * @return array
  313. */
  314. protected function isAddedElementCanBeInGroup(Element $element)
  315. {
  316. $element_tags = $element->getTags();
  317. $groups = array();
  318. foreach ($this->getUser()->getGroupsOwned() as $group)
  319. {
  320. foreach ($element_tags as $element_tag)
  321. {
  322. if ($group->hasThisTag($element_tag->getId()))
  323. {
  324. $groups[] = array(
  325. 'name' => $group->getName(),
  326. 'id' => $group->getId(),
  327. 'url' => $this->generateUrl('ajax_set_element_group', array(
  328. 'token' => $this->getUser()->getPersonalHash(),
  329. 'element_id' => $element->getId(),
  330. 'group_id' => $group->getId()
  331. ))
  332. );
  333. }
  334. }
  335. }
  336. return $groups;
  337. }
  338. /**
  339. * Action non ajax nettoyant la liste de tags du chercheur d'éléments
  340. *
  341. * @return RedirectResponse
  342. */
  343. public function filterClearAction()
  344. {
  345. $es = $this->getElementSearcher();
  346. $es->update(array('tags' => array()));
  347. $this->setElementSearcherParams($es->getParams());
  348. return $this->redirect($this->container->get('request')->headers->get('referer'));
  349. }
  350. /**
  351. * Action non ajax de selection de ses tags favoris pour le chercheur d'élément
  352. *
  353. * @return RedirectResponse
  354. */
  355. public function filterMytagsAction()
  356. {
  357. $this->getElementSearcher(null, true);
  358. return $this->redirect($this->container->get('request')->headers->get('referer'));
  359. }
  360. /**
  361. * Action de récupération ajax de l'id des tags favoris de son profil
  362. *
  363. * @return Response
  364. */
  365. public function getFavoriteTagsAction()
  366. {
  367. if (($response = $this->mustBeConnected()))
  368. {
  369. return $response;
  370. }
  371. // On construit l'element searcher avec les tags favoris
  372. $es = $this->getElementSearcher(null, true);
  373. // Et on retourne les tags
  374. return $this->jsonResponse(array(
  375. 'response' => 'success',
  376. 'tags' => $es->getTags()
  377. ));
  378. }
  379. /**
  380. * Ajout d'un tag en base.
  381. */
  382. public function addTagAction($name, $arguments = null)
  383. {
  384. if (($response = $this->mustBeConnected()))
  385. {
  386. return $response;
  387. }
  388. $tagManager = new TagManager();
  389. $tag = $tagManager->addTag($this->getDoctrine(), $name, $this->getUser(), $arguments);
  390. return $this->jsonResponse(array(
  391. 'status' => 'success',
  392. 'tag_id' => $tag->getId(),
  393. 'tag_name' => $tag->getName()
  394. ));
  395. }
  396. /**
  397. * Action ajax qui ajoute le tags précisé en paramétre aux tags favoris de
  398. * l'utilisateur.
  399. *
  400. * @param int $tag_id
  401. * @param string $token
  402. * @return Response
  403. */
  404. public function addTagToFavoritesAction($tag_id, $token)
  405. {
  406. if (($response = $this->mustBeConnected(true)))
  407. {
  408. return $response;
  409. }
  410. if (!($tag = $this->getDoctrine()->getRepository('MuzichCoreBundle:Tag')
  411. ->findOneById($tag_id)) || $this->getUser()->getPersonalHash() != $token)
  412. {
  413. return $this->jsonResponse(array(
  414. 'status' => 'error',
  415. 'errors' => array('NotFound')
  416. ));
  417. }
  418. $user = $this->getUser();
  419. /**
  420. * Bug lors des tests: L'user n'est pas 'lié' a celui en base par doctrine.
  421. * Docrine le voit si on faire une requete directe.
  422. */
  423. if ($this->container->getParameter('env') == 'test')
  424. {
  425. $user = $this->getDoctrine()->getRepository('MuzichCoreBundle:User')->findOneById(
  426. $this->container->get('security.context')->getToken()->getUser()->getId(),
  427. array()
  428. )->getSingleResult();
  429. }
  430. // On contrôle au préalable que le tag ne fait pas déjà partie des favoris de
  431. // l'utilisateur
  432. if (!$this->getDoctrine()->getRepository('MuzichCoreBundle:UsersTagsFavorites')
  433. ->findOneBy(array(
  434. 'user' => $this->getUserId(),
  435. 'tag' => $tag->getId()
  436. )))
  437. {
  438. // Si il ne l'est pas, on créer ce nouvel objet de relation
  439. $fav = new UsersTagsFavorites();
  440. $fav->setTag($tag);
  441. $fav->setUser($user);
  442. $fav->setPosition(0);
  443. $this->getDoctrine()->getEntityManager()->persist($fav);
  444. $this->getDoctrine()->getEntityManager()->flush();
  445. }
  446. return $this->jsonResponse(array(
  447. 'status' => 'success'
  448. ));
  449. }
  450. /**
  451. * Cette action (ajax) configure l'appartenance d'un élément a un groupe.
  452. * Le groupe et l'élément doivent appartenir a l'utilisateur en cours.
  453. *
  454. * @param int $element_id
  455. * @param int $group_id
  456. * @param string $token
  457. * @return Response
  458. */
  459. public function setElementGroupAction($element_id, $group_id, $token)
  460. {
  461. if (($response = $this->mustBeConnected(true)))
  462. {
  463. return $response;
  464. }
  465. if (!($element = $this->getDoctrine()->getRepository('MuzichCoreBundle:Element')
  466. ->findOneById($element_id))
  467. || !($group = $this->getDoctrine()->getRepository('MuzichCoreBundle:Group')
  468. ->findOneById($group_id))
  469. || $this->getUser()->getPersonalHash() != $token)
  470. {
  471. return $this->jsonResponse(array(
  472. 'status' => 'error',
  473. 'errors' => array('NotFound')
  474. ));
  475. }
  476. if ($element->getOwner()->getId() != $this->getUserId()
  477. || $group->getOwner()->getId() != $this->getUserId()
  478. )
  479. {
  480. return $this->jsonResponse(array(
  481. 'status' => 'error',
  482. 'errors' => array('NotAllowed')
  483. ));
  484. }
  485. // a partir d'ici on a tout ce qu'il faut
  486. $element->setGroup($group);
  487. $this->getDoctrine()->getEntityManager()->persist($element);
  488. $this->getDoctrine()->getEntityManager()->flush();
  489. // On récupère le nouveau dom de l'élément
  490. $html = $this->render('MuzichCoreBundle:SearchElement:element.html.twig', array(
  491. 'element' => $element
  492. ))->getContent();
  493. return $this->jsonResponse(array(
  494. 'status' => 'success',
  495. 'html' => $html,
  496. 'dom_id' => 'element_'.$element->getId()
  497. ));
  498. }
  499. /**
  500. * Action (ajax) permettant de signaler un élément comme contenu non approprié.
  501. *
  502. * @param int $element_id
  503. * @param string $token
  504. * @return Response
  505. */
  506. public function reportElementAction($element_id, $token)
  507. {
  508. if (($response = $this->mustBeConnected(true)))
  509. {
  510. return $response;
  511. }
  512. if (!($element = $this->getDoctrine()->getRepository('MuzichCoreBundle:Element')
  513. ->findOneById($element_id))
  514. || $this->getUser()->getPersonalHash() != $token)
  515. {
  516. return $this->jsonResponse(array(
  517. 'status' => 'error',
  518. 'errors' => array('NotFound')
  519. ));
  520. }
  521. // On utilise le manager de rapport
  522. $erm = new ElementReportManager($element);
  523. $erm->add($this->getUser());
  524. $this->getDoctrine()->getEntityManager()->persist($element);
  525. $this->getDoctrine()->getEntityManager()->flush();
  526. return $this->jsonResponse(array(
  527. 'status' => 'success'
  528. ));
  529. }
  530. /**
  531. * Il arrive que l'on configure le chercheur d'élément de façon a ce qu'il
  532. * affiche une liste d'élément précis (collection d'id). Cette action
  533. * supprime cette configuration de façon a ce que le chercheur fonctionne
  534. * normalement.
  535. *
  536. * @return type
  537. */
  538. public function filterRemoveIdsAction()
  539. {
  540. if (($response = $this->mustBeConnected(true)))
  541. {
  542. return $response;
  543. }
  544. $es = $this->getElementSearcher();
  545. $es->setIds(null);
  546. $es->setIdsDisplay(null);
  547. $this->setElementSearcherParams($es->getParams());
  548. $html = $this->render('MuzichCoreBundle:SearchElement:default.html.twig', array(
  549. 'user' => $this->getUser(),
  550. 'elements' => $es->getElements($this->getDoctrine(), $this->getUserId()),
  551. 'invertcolor' => false
  552. ))->getContent();
  553. return $this->jsonResponse(array(
  554. 'status' => 'success',
  555. 'html' => $html
  556. ));
  557. }
  558. }