CoreController.php 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  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\Util\StrictCanonicalizer;
  15. use Muzich\CoreBundle\Entity\Tag;
  16. class CoreController extends Controller
  17. {
  18. /**
  19. * Action permettant de changer le language
  20. *
  21. * @param string $language
  22. * @return RedirectResponse
  23. */
  24. public function changeLanguageAction($language)
  25. {
  26. if($language != null)
  27. {
  28. $old = $this->get('session')->getLocale();
  29. $this->get('session')->setLocale($language);
  30. }
  31. $url_referer = $this->container->get('request')->headers->get('referer');
  32. $url_referer = str_replace(
  33. $siteurl = $this->container->getParameter('siteurl'),
  34. '',
  35. $url_referer
  36. );
  37. try {
  38. $params = $this->get('router')->match($url_referer);
  39. } catch (ResourceNotFoundException $exc) {
  40. return $this->redirect($this->generateUrl('home', array('_locale' => $language)));
  41. }
  42. $params['_locale'] = $language;
  43. $route = $params['_route'];
  44. unset($params['_route'], $params['_controller']);
  45. $new_url = $this->generateUrl($route, $params);
  46. return new RedirectResponse($new_url);
  47. }
  48. /**
  49. * Cette action permet a un utilisateur de suivre ou de ne plus suivre
  50. * un utilisateur ou un groupe.
  51. *
  52. * @param string $type
  53. * @param int $id
  54. * @param string $salt
  55. */
  56. public function followAction($type, $id, $token)
  57. {
  58. $user = $this->getUser();
  59. /**
  60. * Bug lors des tests: L'user n'est pas 'lié' a celui en base par doctrine.
  61. * Docrine le voit si on faire une requete directe.
  62. */
  63. if ($this->container->getParameter('env') == 'test')
  64. {
  65. $user = $this->getDoctrine()->getRepository('MuzichCoreBundle:User')->findOneById(
  66. $this->container->get('security.context')->getToken()->getUser()->getId(),
  67. array()
  68. )->getSingleResult();
  69. }
  70. // Vérifications préléminaires
  71. if ($user->getPersonalHash() != $token || !in_array($type, array('user', 'group')) || !is_numeric($id))
  72. {
  73. throw $this->createNotFoundException();
  74. }
  75. // On tente de récupérer l'enregistrement FollowUser / FollowGroup
  76. $em = $this->getDoctrine()->getEntityManager();
  77. $Follow = $em
  78. ->getRepository('MuzichCoreBundle:Follow' . ucfirst($type))
  79. ->findOneBy(
  80. array(
  81. 'follower' => $user->getId(),
  82. ($type == 'user') ? 'followed' : 'group' => $id
  83. )
  84. )
  85. ;
  86. // Si il existe déjà c'est qu'il ne veut plus suivre
  87. if ($Follow)
  88. {
  89. // L'utilisateur suis déjà, on doit détruire l'entité
  90. $em->remove($Follow);
  91. $em->flush();
  92. $following = false;
  93. }
  94. // Sinon, c'est qu'il veut le suivre
  95. else
  96. {
  97. // On récupére l'entité a suivre
  98. $followed = $em->getRepository('MuzichCoreBundle:'.ucfirst($type))->find($id);
  99. if (!$followed) {
  100. throw $this->createNotFoundException('No '.$type.' found for id '.$id);
  101. }
  102. // On instancie te renseigne l'objet Follow****
  103. if ($type == 'user') { $Follow = new FollowUser(); }
  104. else { $Follow = new FollowGroup(); }
  105. $Follow->setFollower($user);
  106. if ($type == 'user') { $Follow->setFollowed($followed); }
  107. else { $Follow->setGroup($followed); }
  108. $em->persist($Follow);
  109. $em->flush();
  110. $following = true;
  111. }
  112. if ($this->getRequest()->isXmlHttpRequest())
  113. {
  114. return $this->jsonResponse(array(
  115. 'status' => 'success',
  116. 'following' => $following
  117. ));
  118. }
  119. else
  120. {
  121. return $this->redirect($this->container->get('request')->headers->get('referer'));
  122. }
  123. }
  124. /**
  125. * Procédure d'ajout d'un element
  126. */
  127. public function elementAddAction($group_slug)
  128. {
  129. if ($this->getUser() == 'anon.')
  130. {
  131. if ($this->getRequest()->isXmlHttpRequest())
  132. {
  133. return $this->jsonResponse(array(
  134. 'status' => 'mustbeconnected'
  135. ));
  136. }
  137. else
  138. {
  139. return $this->redirect($this->generateUrl('index'));
  140. }
  141. }
  142. if ($this->getRequest()->getMethod() != 'POST')
  143. {
  144. throw $this->createNotFoundException('Cette ressource n\'est pas accessible');
  145. }
  146. $user = $this->getUser();
  147. $em = $this->getDoctrine()->getEntityManager();
  148. /*
  149. * Contrôle préléminaire si groupe précisé
  150. */
  151. $group = null;
  152. if ($group_slug)
  153. {
  154. $group = $this->findGroupWithSlug($group_slug);
  155. if (!$group->userCanAddElement($this->getUserId()))
  156. {
  157. $group = null;
  158. throw $this->createNotFoundException('Vous ne pouvez pas ajouter d\'éléments a ce groupe');
  159. }
  160. }
  161. $element = new Element();
  162. $element->setType('none');
  163. $form = $this->getAddForm($element);
  164. $form->bindRequest($this->getRequest());
  165. if ($form->isValid())
  166. {
  167. /**
  168. * Bug lors des tests: L'user n'est pas 'lié' a celui en base par doctrine.
  169. * Docrine le voit si on faire une requete directe.
  170. */
  171. if ($this->container->getParameter('env') == 'test')
  172. {
  173. $user = $this->getDoctrine()->getRepository('MuzichCoreBundle:User')->findOneById(
  174. $this->container->get('security.context')->getToken()->getUser()->getId(),
  175. array()
  176. )->getSingleResult();
  177. }
  178. // On utilise le gestionnaire d'élément
  179. $factory = new ElementManager($element, $em, $this->container);
  180. $factory->proceedFill($user);
  181. // Si on a précisé un groupe dans lequel mettre l'element
  182. if ($group)
  183. {
  184. $element->setGroup($group);
  185. $redirect_url = $this->generateUrl('show_group', array('slug' => $group_slug));
  186. }
  187. else
  188. {
  189. $redirect_url = $this->generateUrl('home');
  190. }
  191. $em->persist($element);
  192. $em->flush();
  193. if ($this->getRequest()->isXmlHttpRequest())
  194. {
  195. // Récupération du li
  196. $html = $this->render('MuzichCoreBundle:SearchElement:li.element.html.twig', array(
  197. 'element' => $element,
  198. 'class_color' => 'odd'
  199. ))->getContent();
  200. return $this->jsonResponse(array(
  201. 'status' => 'success',
  202. 'html' => $html
  203. ));
  204. }
  205. else
  206. {
  207. return $this->redirect($redirect_url);
  208. }
  209. }
  210. else
  211. {
  212. if ($this->getRequest()->isXmlHttpRequest())
  213. {
  214. // Récupération des erreurs
  215. $validator = $this->container->get('validator');
  216. $errorList = $validator->validate($form);
  217. foreach ($errorList as $error)
  218. {
  219. $errors[] = $error->getMessage();
  220. }
  221. return $this->jsonResponse(array(
  222. 'status' => 'error',
  223. 'errors' => $errors
  224. ));
  225. }
  226. else
  227. {
  228. if (!$group_slug)
  229. {
  230. $search_object = $this->getElementSearcher();
  231. $search_form = $this->getSearchForm($search_object);
  232. $add_form = $form;
  233. return $this->render('MuzichHomeBundle:Home:index.html.twig', array(
  234. 'search_tags_id' => $search_object->getTags(),
  235. 'user' => $this->getUser(),
  236. 'add_form' => $add_form->createView(),
  237. 'add_form_name' => 'add',
  238. 'search_form' => $search_form->createView(),
  239. 'search_form_name' => 'search',
  240. 'network_public' => $search_object->isNetworkPublic(),
  241. 'elements' => $search_object->getElements($this->getDoctrine(), $this->getUserId()),
  242. 'more_count' => $this->container->getParameter('search_default_count')*2
  243. ));
  244. }
  245. else
  246. {
  247. $group = $this->findGroupWithSlug($group_slug);
  248. $search_object = $this->createSearchObject(array(
  249. 'group_id' => $group->getId()
  250. ));
  251. ($group->getOwner()->getId() == $this->getUserId()) ? $his = true : $his = false;
  252. if ($his || $group->getOpen())
  253. {
  254. $add_form = $form;
  255. }
  256. return $this->render('MuzichHomeBundle:Show:showGroup.html.twig', array(
  257. 'group' => $group,
  258. 'his_group' => ($group->getOwner()->getId() == $this->getUserId()) ? true : false,
  259. 'elements' => $search_object->getElements($this->getDoctrine(), $this->getUserId()),
  260. 'following' => $this->getUser()->isFollowingGroupByQuery($this->getDoctrine(), $group->getId()),
  261. 'user' => $this->getUser(),
  262. 'add_form' => (isset($add_form)) ? $add_form->createView() : null,
  263. 'add_form_name' => (isset($add_form)) ? 'add' : null,
  264. 'more_count' => null,
  265. 'more_route' => 'show_group_more'
  266. ));
  267. }
  268. }
  269. }
  270. }
  271. public function filterClearAction()
  272. {
  273. $es = $this->getElementSearcher();
  274. $es->update(array('tags' => array()));
  275. $this->setElementSearcherParams($es->getParams());
  276. return $this->redirect($this->container->get('request')->headers->get('referer'));
  277. }
  278. public function filterMytagsAction()
  279. {
  280. $this->getElementSearcher(null, true);
  281. return $this->redirect($this->container->get('request')->headers->get('referer'));
  282. }
  283. public function getFavoriteTagsAction()
  284. {
  285. if ($this->getUser() == 'anon.')
  286. {
  287. if ($this->getRequest()->isXmlHttpRequest())
  288. {
  289. return $this->jsonResponse(array(
  290. 'status' => 'mustbeconnected'
  291. ));
  292. }
  293. else
  294. {
  295. return $this->redirect($this->generateUrl('index'));
  296. }
  297. }
  298. // On construit l'element searcher avec les tags favoris
  299. $es = $this->getElementSearcher(null, true);
  300. // Et on retourne les tags
  301. return $this->jsonResponse(array(
  302. 'response' => 'success',
  303. 'tags' => $es->getTags()
  304. ));
  305. }
  306. /**
  307. * Ajout d'un tag en base.
  308. */
  309. public function addTagAction($name, $arguments = null)
  310. {
  311. if ($this->getUser() == 'anon.')
  312. {
  313. if ($this->getRequest()->isXmlHttpRequest())
  314. {
  315. return $this->jsonResponse(array(
  316. 'status' => 'mustbeconnected'
  317. ));
  318. }
  319. else
  320. {
  321. return $this->redirect($this->generateUrl('index'));
  322. }
  323. }
  324. $canonicalizer = new StrictCanonicalizer();
  325. $name_canonicalized = $canonicalizer->canonicalize($name);
  326. // Check avant de commencer: On regarde si ce tag n'existe pas déjà en tag
  327. // public (en cas de gruge)
  328. if (($tag = $this->getDoctrine()->getRepository('MuzichCoreBundle:Tag')
  329. ->findOneBy(array(
  330. 'slug' => $name_canonicalized,
  331. 'tomoderate' => false
  332. ))))
  333. {
  334. // Si il existe déjà pas besoin de l'ajouter on retourne l'id et ne nom
  335. return $this->jsonResponse(array(
  336. 'status' => 'success',
  337. 'tag_id' => $tag->getId(),
  338. 'tag_name' => $tag->getName()
  339. ));
  340. }
  341. // Première étape, on regarde en base si quelqu'un a pas déjà ajouté ce tag
  342. if (($tag = $this->getDoctrine()->getRepository('MuzichCoreBundle:Tag')
  343. ->findOneBy(array(
  344. 'slug' => $name_canonicalized,
  345. 'tomoderate' => true
  346. ))))
  347. {
  348. // Si il existe déjà pas besoin de l'ajouter on retourne l'id et ne nom
  349. // après avoir ajouté cet utilisateurs a la liste de ceux pouvant le voir
  350. $privatesids = json_decode($tag->getPrivateids());
  351. if (!in_array($this->getUserId(), $privatesids))
  352. {
  353. $privatesids[] = (string)$this->getUserId();
  354. }
  355. $tag->setPrivateids(json_encode($privatesids));
  356. $tag->setArguments($tag->getArguments(). " ****" . $this->getUser()->getName()."****: " .$arguments);
  357. $this->getDoctrine()->getEntityManager()->persist($tag);
  358. $this->getDoctrine()->getEntityManager()->flush();
  359. return $this->jsonResponse(array(
  360. 'status' => 'success',
  361. 'tag_id' => $tag->getId(),
  362. 'tag_name' => $tag->getName()
  363. ));
  364. }
  365. else
  366. {
  367. // Sinon on l'ajoute en base
  368. $tag = new Tag();
  369. $tag->setName(ucfirst(strtolower($name)));
  370. $tag->setTomoderate(true);
  371. $tag->setPrivateids(json_encode(array((string)$this->getUserId())));
  372. $tag->setArguments(" ****" . $this->getUser()->getName()."****: " .$arguments);
  373. $this->getDoctrine()->getEntityManager()->persist($tag);
  374. $this->getDoctrine()->getEntityManager()->flush();
  375. return $this->jsonResponse(array(
  376. 'status' => 'success',
  377. 'tag_id' => $tag->getId(),
  378. 'tag_name' => $tag->getName()
  379. ));
  380. }
  381. }
  382. }