ElementController.php 28KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988
  1. <?php
  2. namespace Muzich\CoreBundle\Controller;
  3. use Muzich\CoreBundle\lib\Controller;
  4. use Muzich\CoreBundle\Managers\ElementManager;
  5. use Muzich\CoreBundle\Propagator\EventElement;
  6. use Muzich\CoreBundle\Entity\ElementTagsProposition;
  7. use Symfony\Component\HttpFoundation\Request;
  8. use Muzich\CoreBundle\Entity\Element;
  9. use Muzich\CoreBundle\Util\TagLike;
  10. use Muzich\CoreBundle\Entity\User;
  11. class ElementController extends Controller
  12. {
  13. /**
  14. * Cette méthode est utilisé pour récupérer un objet Element tout en levant
  15. * une erreur si il n'existe pas ou si il n'appartient pas a l'utilisateur en
  16. * cours.
  17. *
  18. * @param int $element_id
  19. * @return Muzich\CoreBundle\Entity\Element
  20. */
  21. protected function checkExistingAndOwned($element_id)
  22. {
  23. if (!($element = $this->getDoctrine()->getRepository('MuzichCoreBundle:Element')
  24. ->findOneById($element_id)))
  25. {
  26. throw $this->createNotFoundException('Not found');
  27. }
  28. if ($element->getOwner()->getId() != $this->getUserId())
  29. {
  30. throw $this->createNotFoundException('Not found');
  31. }
  32. return $element;
  33. }
  34. /**
  35. * Action d'ouverture du formulaire de modification d'un élément.
  36. *
  37. * @param int $element_id
  38. * @return Response
  39. */
  40. public function editAction($element_id)
  41. {
  42. if (($response = $this->mustBeConnected()))
  43. {
  44. return $response;
  45. }
  46. $element = $this->checkExistingAndOwned($element_id);
  47. // On doit faire un chmilblik avec les tags pour
  48. // utiliser le javascript de tags (tagPrompt)
  49. // sur le formulaire
  50. $element_tags = $element->getTags();
  51. $element->setTags($element->getTagsIdsJson());
  52. $form = $this->getAddForm($element);
  53. $search_tags = array();
  54. foreach ($element_tags as $tag)
  55. {
  56. $search_tags[$tag->getId()] = $tag->getName();
  57. }
  58. $template = 'MuzichCoreBundle:Element:ajax.element.edit.html.twig';
  59. if (!$this->getRequest()->isXmlHttpRequest())
  60. {
  61. $template = 'MuzichCoreBundle:Element:element.edit.html.twig';
  62. }
  63. $response = $this->render($template, array(
  64. 'form' => $form->createView(),
  65. 'form_name' => 'element_'.$element->getId(),
  66. 'element_id' => $element->getId(),
  67. 'search_tags' => $search_tags
  68. ));
  69. if ($this->getRequest()->isXmlHttpRequest())
  70. {
  71. return $this->jsonResponse(array(
  72. 'status' => 'success',
  73. 'form_name' => 'element_'.$element->getId(),
  74. 'tags' => $search_tags,
  75. 'html' => $response->getContent()
  76. ));
  77. }
  78. return $response;
  79. }
  80. /**
  81. * Mise a jour des données d'un élément.
  82. *
  83. * @param int $element_id
  84. * @param string $dom_id
  85. * @return Response
  86. */
  87. public function updateAction($element_id, $dom_id)
  88. {
  89. if (($response = $this->mustBeConnected()))
  90. {
  91. return $response;
  92. }
  93. /**
  94. * Bug lors des tests: L'user n'est pas 'lié' a celui en base par doctrine.
  95. * Docrine le voit si on faire une requete directe.
  96. */
  97. $user = $this->getUser();
  98. if ($this->container->getParameter('env') == 'test')
  99. {
  100. $user = $this->getDoctrine()->getRepository('MuzichCoreBundle:User')->findOneById(
  101. $this->container->get('security.context')->getToken()->getUser()->getId(),
  102. array()
  103. )->getSingleResult();
  104. }
  105. $element = $this->checkExistingAndOwned($element_id);
  106. // Si il y a un groupe on le retire pour le bind
  107. $group = $element->getGroup();
  108. $element->setGroup(null);
  109. $form = $this->getAddForm($element);
  110. $form->bindRequest($this->getRequest());
  111. $errors = array();
  112. $html = '';
  113. if ($form->isValid())
  114. {
  115. $status = 'success';
  116. $em = $this->getDoctrine()->getEntityManager();
  117. // On utilise le manager d'élément
  118. $factory = new ElementManager($element, $em, $this->container);
  119. $factory->proceedFill($user);
  120. // Si il y avais un groupe on le remet
  121. $element->setGroup($group);
  122. // On signale que cet user a modifié ses diffusions
  123. $user->setData(User::DATA_DIFF_UPDATED, true);
  124. $em->persist($user);
  125. $em->persist($element);
  126. $em->flush();
  127. // Récupération du li
  128. $html = $this->render('MuzichCoreBundle:SearchElement:element.html.twig', array(
  129. 'element' => $element
  130. ))->getContent();
  131. }
  132. else
  133. {
  134. $status = 'error';
  135. // Récupération des erreurs
  136. $validator = $this->container->get('validator');
  137. $errorList = $validator->validate($form);
  138. foreach ($errorList as $error)
  139. {
  140. $errors[] = $this->trans($error->getMessage(), array(), 'validators');
  141. }
  142. }
  143. if ($this->getRequest()->isXmlHttpRequest())
  144. {
  145. return $this->jsonResponse(array(
  146. 'status' => $status,
  147. 'dom_id' => $dom_id,
  148. 'html' => $html,
  149. 'errors' => $errors
  150. ));
  151. }
  152. if ($status == 'success')
  153. {
  154. return $this->redirect($this->generateUrl('home'));
  155. }
  156. $element->setTagsWithIds(
  157. $this->getDoctrine()->getEntityManager(),
  158. json_decode($element->getTags())
  159. );
  160. return $this->render('MuzichCoreBundle:Element:element.edit.html.twig', array(
  161. 'form' => $form->createView(),
  162. 'form_name' => 'element_'.$element->getId(),
  163. 'element_id' => $element->getId(),
  164. 'search_tags' => $element->getTagsIdsJson()
  165. ));
  166. }
  167. /**
  168. * Suppression d'un élément.
  169. *
  170. * @param int $element_id
  171. * @return Response
  172. */
  173. public function removeAction($element_id)
  174. {
  175. if (($response = $this->mustBeConnected()))
  176. {
  177. return $response;
  178. }
  179. try {
  180. $element = $this->checkExistingAndOwned($element_id);
  181. $em = $this->getDoctrine()->getEntityManager();
  182. $event = new EventElement($this->container);
  183. $event->elementRemoved($element);
  184. $em->persist($element->getOwner());
  185. $em->remove($element);
  186. /**
  187. * Bug lors des tests: L'user n'est pas 'lié' a celui en base par doctrine.
  188. * Docrine le voit si on faire une requete directe.
  189. */
  190. $user = $this->getUser();
  191. if ($this->container->getParameter('env') == 'test')
  192. {
  193. $user = $this->getDoctrine()->getRepository('MuzichCoreBundle:User')->findOneById(
  194. $this->container->get('security.context')->getToken()->getUser()->getId(),
  195. array()
  196. )->getSingleResult();
  197. }
  198. // On signale que cet user a modifié ses diffusions
  199. $user->setData(User::DATA_DIFF_UPDATED, true);
  200. $em->persist($user);
  201. $em->flush();
  202. if ($this->getRequest()->isXmlHttpRequest())
  203. {
  204. return $this->jsonResponse(array('status' => 'success'));
  205. }
  206. $this->setFlash('success', 'element.remove.success');
  207. return $this->redirect($this->container->get('request')->headers->get('referer'));
  208. }
  209. catch(Exception $e)
  210. {
  211. if ($this->getRequest()->isXmlHttpRequest())
  212. {
  213. return $this->jsonResponse(array('status' => 'error'));
  214. }
  215. $this->setFlash('error', 'element.remove.error');
  216. return $this->redirect($this->container->get('request')->headers->get('referer'));
  217. }
  218. }
  219. /**
  220. * Cette procédure retourne le lien a afficher sur la page home permettant
  221. * d'afficher des élément apparus entre temps.
  222. *
  223. * @param int $count
  224. * @return type
  225. */
  226. protected function getcountNewMessage($count)
  227. {
  228. if ($count == 1)
  229. {
  230. $transid = 'tags.new.has_news_one';
  231. $transidlink = 'tags.new.has_news_link_one';
  232. }
  233. else if ($count == 0)
  234. {
  235. return '';
  236. }
  237. else
  238. {
  239. $transid = 'tags.new.has_news';
  240. $transidlink = 'tags.new.has_news_link';
  241. }
  242. if ($count > ($limit = $this->container->getParameter('search_default_count')))
  243. {
  244. $link = $this->trans(
  245. 'tags.new.has_news_link_more_x',
  246. array(
  247. '%x%' => $limit
  248. ),
  249. 'userui'
  250. );
  251. }
  252. else
  253. {
  254. $link = $this->trans(
  255. $transidlink,
  256. array(),
  257. 'userui'
  258. );
  259. }
  260. $link = '<a href="#" class="show_new_elements" >'.$link.'</a>';
  261. return $this->trans(
  262. $transid,
  263. array(
  264. '%count%' => $count,
  265. '%link%' => $link
  266. ),
  267. 'userui'
  268. );
  269. }
  270. /**
  271. * Retourne le nombre de nouveaux éléments possible
  272. *
  273. * @param int $refid
  274. */
  275. public function countNewsAction($refid)
  276. {
  277. if (!$this->getRequest()->isXmlHttpRequest())
  278. {
  279. return $this->redirect($this->generateUrl('index'));
  280. }
  281. if (($response = $this->mustBeConnected()))
  282. {
  283. return $response;
  284. }
  285. if ($this->getRequest()->getMethod() != 'POST')
  286. {
  287. throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException();
  288. }
  289. /*
  290. * On met à jour l'ElementSearcher avec le form
  291. */
  292. $es = $this->getElementSearcher(null, true);
  293. $search_form = $this->getSearchForm($es);
  294. $search_form->bindRequest($this->getRequest());
  295. if ($search_form->isValid())
  296. {
  297. $es->update($search_form->getData());
  298. }
  299. $es->update(array(
  300. // On veux de nouveaux éléments
  301. 'searchnew' => true,
  302. // Notre id de référence
  303. 'id_limit' => $refid
  304. ));
  305. $count = $es->getElements($this->getDoctrine(), $this->getUserId(), 'count');
  306. return $this->jsonResponse(array(
  307. 'status' => 'success',
  308. 'count' => $count,
  309. 'message' => $this->getcountNewMessage($count)
  310. ));
  311. }
  312. /**
  313. * Cette action, utilisé en ajax seulement, retourne les x nouveaux éléments
  314. * depuis le refid transmis. Tout en respectant le filtre en cours.
  315. *
  316. * @param int $refid identifiant de l'élément de référence
  317. *
  318. * @return jsonResponse
  319. */
  320. public function getNewsAction($refid)
  321. {
  322. if (!$this->getRequest()->isXmlHttpRequest())
  323. {
  324. return $this->redirect($this->generateUrl('index'));
  325. }
  326. if (($response = $this->mustBeConnected()))
  327. {
  328. return $response;
  329. }
  330. if ($this->getRequest()->getMethod() != 'POST')
  331. {
  332. throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException();
  333. }
  334. /*
  335. * On met à jour l'ElementSearcher avec le form
  336. */
  337. $es = $this->getElementSearcher(null, true);
  338. $search_form = $this->getSearchForm($es);
  339. $search_form->bindRequest($this->getRequest());
  340. if ($search_form->isValid())
  341. {
  342. $es->update($search_form->getData());
  343. }
  344. $es->update(array(
  345. // On veux de nouveaux éléments
  346. 'searchnew' => true,
  347. // Notre id de référence
  348. 'id_limit' => $refid,
  349. // On en veut qu'un certain nombres
  350. 'count' => $this->container->getParameter('search_default_count')
  351. ));
  352. // Récupération de ces nouveaux élméents
  353. $elements = $es->getElements($this->getDoctrine(), $this->getUserId());
  354. // On en fait un rendu graphique
  355. $html_elements = $this->render('MuzichCoreBundle:SearchElement:default.html.twig', array(
  356. 'user' => $this->getUser(),
  357. 'elements' => $elements,
  358. 'invertcolor' => false
  359. ))->getContent();
  360. // On calcule le nouveau compte de nouveaux
  361. $count = 0;
  362. if (count($elements))
  363. {
  364. $es->update(array(
  365. // On veux de nouveaux éléments
  366. 'searchnew' => true,
  367. // Notre id de référence
  368. 'id_limit' => $elements[0]->getId(),
  369. // On n'en récupère que x
  370. 'count' => $this->container->getParameter('search_default_count')
  371. ));
  372. $count = $es->getElements($this->getDoctrine(), $this->getUserId(), 'count');
  373. }
  374. return $this->jsonResponse(array(
  375. 'status' => 'success',
  376. 'html' => $html_elements,
  377. 'count' => $count,
  378. 'message' => $this->getcountNewMessage($count)
  379. ));
  380. }
  381. /**
  382. * Action (ajax) ajoutant son vote "good" sur un élément
  383. *
  384. * @param int $element_id
  385. * @param string $token
  386. * @return Response
  387. */
  388. public function addVoteGoodAction($element_id, $token)
  389. {
  390. if (($response = $this->mustBeConnected(true)))
  391. {
  392. return $response;
  393. }
  394. if (!($element = $this->getDoctrine()->getRepository('MuzichCoreBundle:Element')
  395. ->findOneById($element_id)) || $this->getUser()->getPersonalHash() != $token)
  396. {
  397. return $this->jsonResponse(array(
  398. 'status' => 'error',
  399. 'errors' => array('NotFound')
  400. ));
  401. }
  402. if ($element->getOwner()->getId() == $this->getUserId())
  403. {
  404. return $this->jsonResponse(array(
  405. 'status' => 'error',
  406. 'errors' => array('NotAllowed')
  407. ));
  408. }
  409. // On ajoute un vote a l'élément
  410. $element->addVoteGood($this->getUser()->getId());
  411. // Puis on lance les actions propagés par ce vote
  412. $event = new EventElement($this->container);
  413. $event->onePointAdded($element);
  414. $this->getDoctrine()->getEntityManager()->persist($element);
  415. $this->getDoctrine()->getEntityManager()->flush();
  416. return $this->jsonResponse(array(
  417. 'status' => 'success',
  418. 'data' => array(
  419. 'a' => array(
  420. 'href' => $this->generateUrl('ajax_element_remove_vote_good', array(
  421. 'element_id' => $element->getId(),
  422. 'token' => $this->getUser()->getPersonalHash()
  423. ))
  424. ),
  425. 'img' => array(
  426. 'src' => $this->getAssetUrl('bundles/muzichcore/img/up_b.png')
  427. ),
  428. 'element' => array(
  429. 'points' => $element->getPoints()
  430. )
  431. )
  432. ));
  433. }
  434. /**
  435. * Action (ajax) de retrait de son vote good
  436. *
  437. * @param int $element_id
  438. * @param string $token
  439. * @return Response
  440. */
  441. public function removeVoteGoodAction($element_id, $token)
  442. {
  443. if (($response = $this->mustBeConnected(true)))
  444. {
  445. return $response;
  446. }
  447. if (!($element = $this->getDoctrine()->getRepository('MuzichCoreBundle:Element')
  448. ->findOneById($element_id)) || $this->getUser()->getPersonalHash() != $token)
  449. {
  450. return $this->jsonResponse(array(
  451. 'status' => 'error',
  452. 'errors' => array('NotFound')
  453. ));
  454. }
  455. if ($element->getOwner()->getId() == $this->getUserId())
  456. {
  457. return $this->jsonResponse(array(
  458. 'status' => 'error',
  459. 'errors' => array('NotAllowed')
  460. ));
  461. }
  462. // Retrait du vote good
  463. $element->removeVoteGood($this->getUser()->getId());
  464. // Puis on lance les actions propagés par retrait de vote
  465. $event = new EventElement($this->container);
  466. $event->onePointRemoved($element);
  467. $this->getDoctrine()->getEntityManager()->persist($element);
  468. $this->getDoctrine()->getEntityManager()->flush();
  469. return $this->jsonResponse(array(
  470. 'status' => 'success',
  471. 'data' => array(
  472. 'a' => array(
  473. 'href' => $this->generateUrl('ajax_element_add_vote_good', array(
  474. 'element_id' => $element->getId(),
  475. 'token' => $this->getUser()->getPersonalHash()
  476. ))
  477. ),
  478. 'img' => array(
  479. 'src' => $this->getAssetUrl('bundles/muzichcore/img/up_bw.png')
  480. ),
  481. 'element' => array(
  482. 'points' => $element->getPoints()
  483. )
  484. )
  485. ));
  486. }
  487. /**
  488. * Retourne un json avec le form permettant a l'utilisateur de proposer des
  489. * tags sur un élément.
  490. *
  491. * @param int $element_id
  492. * @return Response
  493. */
  494. public function proposeTagsOpenAction($element_id)
  495. {
  496. if (($response = $this->mustBeConnected(true)))
  497. {
  498. return $response;
  499. }
  500. if (!($element = $this->getDoctrine()->getRepository('MuzichCoreBundle:Element')
  501. ->findOneById($element_id)))
  502. {
  503. return $this->jsonResponse(array(
  504. 'status' => 'error',
  505. 'errors' => array('NotFound')
  506. ));
  507. }
  508. $search_tags = array();
  509. foreach ($element->getTags() as $tag)
  510. {
  511. $search_tags[$tag->getId()] = $tag->getName();
  512. }
  513. $element->setTags($element->getTagsIdsJson());
  514. $form = $this->getAddForm($element, 'element_tag_proposition_'.$element->getId());
  515. $response = $this->render('MuzichCoreBundle:Element:tag.proposition.html.twig', array(
  516. 'form' => $form->createView(),
  517. 'form_name' => 'element_tag_proposition_'.$element->getId(),
  518. 'element_id' => $element->getId(),
  519. 'search_tags' => $search_tags
  520. ));
  521. return $this->jsonResponse(array(
  522. 'status' => 'success',
  523. 'form_name' => 'element_tag_proposition_'.$element->getId(),
  524. 'tags' => $search_tags,
  525. 'html' => $response->getContent()
  526. ));
  527. }
  528. public function proposeTagsProceedAction($element_id, $token)
  529. {
  530. if (($response = $this->mustBeConnected(true)))
  531. {
  532. return $response;
  533. }
  534. if (!($element = $this->getDoctrine()->getRepository('MuzichCoreBundle:Element')
  535. ->findOneById($element_id)) || $token != $this->getUser()->getPersonalHash())
  536. {
  537. return $this->jsonResponse(array(
  538. 'status' => 'error',
  539. 'errors' => array('NotFound')
  540. ));
  541. }
  542. // On ne doit pas pouvoir proposer de tags sur son propre élément
  543. if ($element->getOwner()->getId() == $this->getUserId())
  544. {
  545. return $this->jsonResponse(array(
  546. 'status' => 'error',
  547. 'errors' => array('NotAllowed')
  548. ));
  549. }
  550. $values = $this->getRequest()->request->get('element_tag_proposition_'.$element->getId());
  551. $tags_ids = json_decode($values['tags'], true);
  552. $tags = array();
  553. if (count($tags_ids))
  554. {
  555. // On récupère les tags en base
  556. $tags = $this->getDoctrine()->getEntityManager()->getRepository('MuzichCoreBundle:Tag')
  557. ->getTagsWithIds($tags_ids)
  558. ;
  559. }
  560. if (!count($tags))
  561. {
  562. return $this->jsonResponse(array(
  563. 'status' => 'error',
  564. 'errors' => array($this->trans('element.tag_proposition.form.error.empty', array(), 'elements'))
  565. ));
  566. }
  567. /**
  568. * Bug lors des tests: L'user n'est pas 'lié' a celui en base par doctrine.
  569. * Docrine le voit si on faire une requete directe.
  570. */
  571. $user = $this->getUser();
  572. if ($this->container->getParameter('env') == 'test')
  573. {
  574. $user = $this->getDoctrine()->getRepository('MuzichCoreBundle:User')->findOneById(
  575. $this->container->get('security.context')->getToken()->getUser()->getId(),
  576. array()
  577. )->getSingleResult();
  578. }
  579. $proposition = new ElementTagsProposition();
  580. $proposition->setElement($element);
  581. $proposition->setUser($user);
  582. $date = new \DateTime(date('Y-m-d H:i:s'));
  583. $proposition->setCreated($date);
  584. foreach ($tags as $tag)
  585. {
  586. // Si le tag est a modérer, il faut que le propriétaire de l'élément
  587. // puisse voir ce tag, afin d'accepter en toute connaisance la proposition.
  588. if ($tag->getTomoderate())
  589. {
  590. if (!$tag->hasIdInPrivateIds($element->getOwner()->getId()))
  591. {
  592. // Si son id n'y est pas on la rajoute afin que le proprio puisse voir
  593. // ces nouveau tags
  594. $private_ids = json_decode($tag->getPrivateids(), true);
  595. $private_ids[] = $element->getOwner()->getId();
  596. $tag->setPrivateids(json_encode($private_ids));
  597. $this->getDoctrine()->getEntityManager()->persist($tag);
  598. }
  599. }
  600. $proposition->addTag($tag);
  601. }
  602. $element->setHasTagProposition(true);
  603. $this->getDoctrine()->getEntityManager()->persist($element);
  604. $this->getDoctrine()->getEntityManager()->persist($proposition);
  605. // Notifs etc
  606. $event = new EventElement($this->container);
  607. $event->tagsProposed($element);
  608. $this->getDoctrine()->getEntityManager()->flush();
  609. return $this->jsonResponse(array(
  610. 'status' => 'success',
  611. 'dom_id' => 'element_'.$element->getId()
  612. ));
  613. }
  614. public function proposedTagsViewAction($element_id)
  615. {
  616. if (($response = $this->mustBeConnected(true)))
  617. {
  618. return $response;
  619. }
  620. if (!($element = $this->getDoctrine()->getRepository('MuzichCoreBundle:Element')
  621. ->findOneById($element_id)))
  622. {
  623. return $this->jsonResponse(array(
  624. 'status' => 'error',
  625. 'errors' => array('NotFound')
  626. ));
  627. }
  628. if ($element->getOwner()->getId() != $this->getUserId())
  629. {
  630. return $this->jsonResponse(array(
  631. 'status' => 'error',
  632. 'errors' => array('NotAllowed')
  633. ));
  634. }
  635. // On récupére toute les propsotions pour cet élément
  636. $propositions = $this->getDoctrine()->getEntityManager()->getRepository('MuzichCoreBundle:ElementTagsProposition')
  637. ->findByElement($element->getId())
  638. ;
  639. $response = $this->render('MuzichCoreBundle:Element:tag.propositions.html.twig', array(
  640. 'propositions' => $propositions,
  641. 'element_id' => $element->getId()
  642. ));
  643. return $this->jsonResponse(array(
  644. 'status' => 'success',
  645. 'html' => $response->getContent()
  646. ));
  647. }
  648. public function proposedTagsAcceptAction($proposition_id, $token)
  649. {
  650. if (($response = $this->mustBeConnected(true)))
  651. {
  652. return $response;
  653. }
  654. if (!($proposition = $this->getDoctrine()->getRepository('MuzichCoreBundle:ElementTagsProposition')
  655. ->findOneById($proposition_id)) || $token != $this->getUser()->getPersonalHash())
  656. {
  657. return $this->jsonResponse(array(
  658. 'status' => 'error',
  659. 'errors' => array('NotFound')
  660. ));
  661. }
  662. // On commence par appliquer les nouveaux tags a l'élément
  663. $element = $proposition->getElement();
  664. $element->setTags(null);
  665. foreach ($proposition->getTags() as $tag)
  666. {
  667. $element->addTag($tag);
  668. }
  669. $element->setHasTagProposition(false);
  670. $element->setNeedTags(false);
  671. $this->getDoctrine()->getEntityManager()->persist($element);
  672. $event = new EventElement($this->container);
  673. $event->tagsAccepteds($proposition);
  674. $propositions = $this->getDoctrine()->getEntityManager()->getRepository('MuzichCoreBundle:ElementTagsProposition')
  675. ->findByElement($element->getId())
  676. ;
  677. // On supprime les proposition liés a cet élement
  678. foreach ($propositions as $proposition)
  679. {
  680. $this->getDoctrine()->getEntityManager()->remove($proposition);
  681. }
  682. $this->getDoctrine()->getEntityManager()->flush();
  683. $element = $this->getDoctrine()->getRepository('MuzichCoreBundle:Element')
  684. ->findOneById($element->getId())
  685. ;
  686. // On récupère l'html de l'élément
  687. $html = $this->render('MuzichCoreBundle:SearchElement:element.html.twig', array(
  688. 'element' => $element
  689. ))->getContent();
  690. return $this->jsonResponse(array(
  691. 'status' => 'success',
  692. 'html' => $html
  693. ));
  694. }
  695. public function proposedTagsRefuseAction($element_id, $token)
  696. {
  697. if (($response = $this->mustBeConnected(true)))
  698. {
  699. return $response;
  700. }
  701. if (!($element = $this->getDoctrine()->getRepository('MuzichCoreBundle:Element')
  702. ->findOneById($element_id)) || $token != $this->getUser()->getPersonalHash())
  703. {
  704. return $this->jsonResponse(array(
  705. 'status' => 'error',
  706. 'errors' => array('NotFound')
  707. ));
  708. }
  709. // On supprime les proposition liés a cet élement
  710. $propositions = $this->getDoctrine()->getEntityManager()->getRepository('MuzichCoreBundle:ElementTagsProposition')
  711. ->findByElement($element->getId())
  712. ;
  713. foreach ($propositions as $proposition)
  714. {
  715. $this->getDoctrine()->getEntityManager()->remove($proposition);
  716. }
  717. // On spécifie qu'il n'y as plus de proposition
  718. $element->setHasTagProposition(false);
  719. $this->getDoctrine()->getEntityManager()->persist($element);
  720. $this->getDoctrine()->getEntityManager()->flush();
  721. return $this->jsonResponse(array(
  722. 'status' => 'success'
  723. ));
  724. }
  725. public function reshareAction(Request $request, $element_id, $token)
  726. {
  727. if (($response = $this->mustBeConnected(true)))
  728. {
  729. return $response;
  730. }
  731. if ($this->getUser()->getPersonalHash('reshare_'.$element_id) != $token)
  732. {
  733. throw new \Symfony\Component\HttpFoundation\File\Exception\AccessDeniedException();
  734. }
  735. if (!($element = $this->getDoctrine()->getRepository('MuzichCoreBundle:Element')
  736. ->findOneById($element_id)))
  737. {
  738. throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException();
  739. }
  740. if ($element->getOwner()->getId() == $this->getUserId())
  741. {
  742. throw new \Symfony\Component\HttpFoundation\File\Exception\AccessDeniedException();
  743. }
  744. /**
  745. * Bug lors des tests: L'user n'est pas 'lié' a celui en base par doctrine.
  746. * Docrine le voit si on faire une requete directe.
  747. */
  748. $user = $this->getUser();
  749. if ($this->container->getParameter('env') == 'test')
  750. {
  751. $user = $this->getDoctrine()->getRepository('MuzichCoreBundle:User')->findOneById(
  752. $this->container->get('security.context')->getToken()->getUser()->getId(),
  753. array()
  754. )->getSingleResult();
  755. }
  756. // Pour le repartage on crée un nouvel élément
  757. $element_reshared = new Element();
  758. $element_reshared->setUrl($element->getUrl());
  759. $element_reshared->setName($element->getName());
  760. $element_reshared->addTags($element->getTags());
  761. $element_reshared->setParent($element);
  762. // On utilise le gestionnaire d'élément
  763. $factory = new ElementManager($element_reshared, $this->getEntityManager(), $this->container);
  764. $factory->proceedFill($user, false);
  765. // On se retrouve maintenant avec un nouvel element tout neuf
  766. $this->persist($element_reshared);
  767. $this->flush();
  768. $html_element = $this->render('MuzichCoreBundle:SearchElement:li.element.html.twig', array(
  769. 'element' => $element_reshared,
  770. 'class_color' => 'odd' // TODO: n'est plus utilisé
  771. ))->getContent();
  772. return $this->jsonResponse(array(
  773. 'status' => 'success',
  774. 'html' => $html_element,
  775. 'groups' => $this->isAddedElementCanBeInGroup($element_reshared)
  776. ));
  777. }
  778. protected function findTagsWithProposeds($tags)
  779. {
  780. $tag_like = new TagLike($this->getDoctrine());
  781. $tags_with_likes = array();
  782. foreach ($tags as $tag_name)
  783. {
  784. // On va determiner si on connais ces tags
  785. $tag_like_tag = $tag_like->getSimilarTags($tag_name, $this->getUserId());
  786. // Premièrement: Si on a trouvé des équivalents en base
  787. if (array_key_exists('tags', $tag_like_tag))
  788. {
  789. if (count($tag_like_tag['tags']))
  790. {
  791. // Deuxièmement: Si nos algorythmes on déterminés qu'on l'a en base
  792. if ($tag_like_tag['same_found'])
  793. {
  794. // A ce moment là on le considère comme "bon"
  795. // Et on prend le premier
  796. $tags_with_likes[] = array(
  797. 'original_name' => $tag_name,
  798. 'like_found' => true,
  799. 'like' => $tag_like_tag['tags'][0]
  800. );
  801. }
  802. // On considère ce tag comme inconnu, l'utilisateur peut toute fois
  803. // l'ajouté a notre base.
  804. else
  805. {
  806. $tags_with_likes[] = array(
  807. 'original_name' => $tag_name,
  808. 'like_found' => false,
  809. 'like' => array()
  810. );
  811. }
  812. }
  813. }
  814. }
  815. return $tags_with_likes;
  816. }
  817. public function getDatasApiAction(Request $request)
  818. {
  819. if (($response = $this->mustBeConnected(true)))
  820. {
  821. return $response;
  822. }
  823. $url = null;
  824. if (count(($element_add_values = $request->get('element_add'))))
  825. {
  826. $url = $element_add_values['url'];
  827. }
  828. // On vérifie la tête de l'url quand même
  829. if (filter_var($url, FILTER_VALIDATE_URL) === false)
  830. {
  831. return $this->jsonResponse(array(
  832. 'status' => 'error',
  833. 'errors' => array(
  834. $this->trans('error.url.invalid', array(), 'validators')
  835. )
  836. ));
  837. }
  838. // On construit l'élèment qui va nous permettre de travailler avec l'api
  839. $element = new Element();
  840. $element->setUrl($url);
  841. $factory = new ElementManager($element, $this->getEntityManager(), $this->container);
  842. $factory->proceedFill($this->getUser());
  843. // On gère les tags proposés
  844. $tags_propositions = array();
  845. if (count($tags = $element->getProposedTags()))
  846. {
  847. $tags_propositions = $this->findTagsWithProposeds($tags);
  848. }
  849. return $this->jsonResponse(array(
  850. 'status' => 'success',
  851. 'name' => $element->getProposedName(),
  852. 'tags' => $tags_propositions,
  853. 'thumb' => $element->getThumbnailUrl()
  854. ));
  855. }
  856. }