ElementController.php 35KB

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