CoreController.php 18KB

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