ElementController.php 35KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214
  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->bind($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, $token)
  178. {
  179. if (($response = $this->mustBeConnected()))
  180. {
  181. return $response;
  182. }
  183. if ($token != $this->getUser()->getPersonalHash($element_id))
  184. {
  185. return $this->jsonResponse(array('status' => 'error'));
  186. }
  187. try {
  188. $element = $this->checkExistingAndOwned($element_id);
  189. $em = $this->getDoctrine()->getEntityManager();
  190. $event = new EventElement($this->container);
  191. $event->elementRemoved($element);
  192. $em->persist($element->getOwner());
  193. $em->remove($element);
  194. /**
  195. * Bug lors des tests: L'user n'est pas 'lié' a celui en base par doctrine.
  196. * Docrine le voit si on faire une requete directe.
  197. */
  198. $user = $this->getUser();
  199. if ($this->container->getParameter('env') == 'test')
  200. {
  201. $user = $this->getDoctrine()->getRepository('MuzichCoreBundle:User')->findOneById(
  202. $this->container->get('security.context')->getToken()->getUser()->getId(),
  203. array()
  204. )->getSingleResult();
  205. }
  206. // On signale que cet user a modifié ses diffusions
  207. $user->setData(User::DATA_DIFF_UPDATED, true);
  208. $em->persist($user);
  209. $em->flush();
  210. if ($this->getRequest()->isXmlHttpRequest())
  211. {
  212. return $this->jsonResponse(array('status' => 'success'));
  213. }
  214. $this->setFlash('success', 'element.remove.success');
  215. return $this->redirect($this->container->get('request')->headers->get('referer'));
  216. }
  217. catch(Exception $e)
  218. {
  219. if ($this->getRequest()->isXmlHttpRequest())
  220. {
  221. return $this->jsonResponse(array('status' => 'error'));
  222. }
  223. $this->setFlash('error', 'element.remove.error');
  224. return $this->redirect($this->container->get('request')->headers->get('referer'));
  225. }
  226. }
  227. /**
  228. * Cette procédure retourne le lien a afficher sur la page home permettant
  229. * d'afficher des élément apparus entre temps.
  230. *
  231. * @param int $count
  232. * @return type
  233. */
  234. protected function getcountNewMessage($count)
  235. {
  236. if ($count == 1)
  237. {
  238. $transid = 'tags.new.has_news_one';
  239. $transidlink = 'tags.new.has_news_link_one';
  240. }
  241. else if ($count == 0)
  242. {
  243. return '';
  244. }
  245. else
  246. {
  247. $transid = 'tags.new.has_news';
  248. $transidlink = 'tags.new.has_news_link';
  249. }
  250. if ($count > ($limit = $this->container->getParameter('search_default_count')))
  251. {
  252. $link = $this->trans(
  253. 'tags.new.has_news_link_more_x',
  254. array(
  255. '%x%' => $limit
  256. ),
  257. 'userui'
  258. );
  259. }
  260. else
  261. {
  262. $link = $this->trans(
  263. $transidlink,
  264. array(),
  265. 'userui'
  266. );
  267. }
  268. $link = '<a href="#" class="show_new_elements" >'.$link.'</a>';
  269. return $this->trans(
  270. $transid,
  271. array(
  272. '%count%' => $count,
  273. '%link%' => $link
  274. ),
  275. 'userui'
  276. );
  277. }
  278. /**
  279. * Retourne le nombre de nouveaux éléments possible
  280. *
  281. * @param int $refid
  282. */
  283. public function countNewsAction($refid)
  284. {
  285. if (!$this->getRequest()->isXmlHttpRequest())
  286. {
  287. return $this->redirect($this->generateUrl('index'));
  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->bind($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(true), '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->bind($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($element_id) != $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($element->getId())
  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($element_id) != $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($element->getId())
  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($proposition_id))
  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($element_id))
  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()->getEntityManager());
  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 = trim($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, $element_id, $type, $data, $show_type = null, $show_id = null)
  887. {
  888. $elements = array();
  889. $elements_json = array();
  890. if ($type == 'filter')
  891. {
  892. // Pour cette option on utilise le dernier filtre appliqué
  893. $search_object = $this->getElementSearcher();
  894. $search_object->update(array(
  895. 'count' => $this->container->getParameter('autoplay_max_elements'),
  896. 'id_limit' => $element_id+1
  897. ));
  898. $elements = $search_object->getElements($this->getDoctrine(), $this->getUserId(true));
  899. }
  900. elseif ($type == 'show')
  901. {
  902. if ($show_type != 'user' && $show_type != 'group')
  903. {
  904. throw $this->createNotFoundException('Not found');
  905. }
  906. $tags = null;
  907. $tag_ids = json_decode($data);
  908. $search_object = new ElementSearcher();
  909. if (count($tag_ids))
  910. {
  911. $tags = array();
  912. foreach ($tag_ids as $id)
  913. {
  914. $tags[$id] = $id;
  915. }
  916. }
  917. $search_object->init(array(
  918. 'tags' => $tags,
  919. $show_type.'_id' => $show_id,
  920. 'count' => $this->container->getParameter('autoplay_max_elements'),
  921. 'id_limit' => $element_id+1
  922. ));
  923. $elements = $search_object->getElements($this->getDoctrine(), $this->getUserId());
  924. }
  925. elseif ($type == 'favorite')
  926. {
  927. $tags = null;
  928. $tag_ids = json_decode($data);
  929. $search_object = new ElementSearcher();
  930. if (count($tag_ids))
  931. {
  932. $tags = array();
  933. foreach ($tag_ids as $id)
  934. {
  935. $tags[$id] = $id;
  936. }
  937. }
  938. $search_object->init(array(
  939. 'tags' => $tags,
  940. 'user_id' => $show_id,
  941. 'favorite' => true,
  942. 'count' => $this->container->getParameter('autoplay_max_elements'),
  943. 'id_limit' => $element_id+1
  944. ));
  945. $elements = $search_object->getElements($this->getDoctrine(), $this->getUserId(true));
  946. }
  947. if (count($elements))
  948. {
  949. // On récupère les élements
  950. $autoplaym = new AutoplayManager($elements, $this->container);
  951. $elements_json = $autoplaym->getList();
  952. }
  953. return $this->jsonResponse(array(
  954. 'status' => 'success',
  955. 'data' => $elements_json
  956. ));
  957. }
  958. public function getOneDomAction(Request $request, $element_id, $type)
  959. {
  960. if (!in_array($type, array('autoplay')))
  961. {
  962. return $this->jsonResponse(array(
  963. 'status' => 'error',
  964. 'errors' => array('NotAllowed')
  965. ));
  966. }
  967. // variables pour le template
  968. $display_edit_actions = true;
  969. $display_player = true;
  970. $display_comments = true;
  971. if ($type == 'autoplay')
  972. {
  973. $display_edit_actions = false;
  974. $display_player = false;
  975. $display_comments = false;
  976. }
  977. // On prépare la récupèration de l'élèment
  978. $es = new ElementSearcher();
  979. $es->init(array(
  980. 'ids' => array($element_id)
  981. ));
  982. if (!($element = $es->getElements($this->getDoctrine(), $this->getUserId(true), 'single')))
  983. {
  984. throw $this->createNotFoundException('Not found');
  985. }
  986. $html = $this->render('MuzichCoreBundle:SearchElement:element.html.twig', array(
  987. 'element' => $element,
  988. 'display_edit_actions' => $display_edit_actions,
  989. 'display_player' => $display_player,
  990. 'display_comments' => $display_comments
  991. ))->getContent();
  992. return $this->jsonResponse(array(
  993. 'status' => 'success',
  994. 'data' => $html
  995. ));
  996. }
  997. public function geJamendotStreamDatasAction(Request $request, $element_id)
  998. {
  999. if (!($element = $this->getDoctrine()->getRepository('MuzichCoreBundle:Element')
  1000. ->findOneById($element_id)))
  1001. {
  1002. throw $this->createNotFoundException('Not found');
  1003. }
  1004. $manager = new ElementManager($element, $this->getEntityManager(), $this->container);
  1005. $stream_data = $manager->getFactory()->getStreamData();
  1006. return $this->jsonResponse(array(
  1007. 'status' => 'success',
  1008. 'data' => $stream_data,
  1009. ));
  1010. }
  1011. public function getEmbedCodeAction($element_id)
  1012. {
  1013. if (!$element_id)
  1014. {
  1015. return $this->jsonNotFoundResponse();
  1016. }
  1017. if (!($element = $this->getDoctrine()->getRepository('MuzichCoreBundle:Element')
  1018. ->findOneById($element_id)))
  1019. {
  1020. return $this->jsonNotFoundResponse();
  1021. }
  1022. return $this->jsonResponse(array(
  1023. 'status' => 'success',
  1024. 'data' => $element->getEmbed(),
  1025. ));
  1026. }
  1027. public function removeFromGroupAction($group_id, $element_id, $token)
  1028. {
  1029. if (!($group = $this->getDoctrine()->getRepository('MuzichCoreBundle:Group')
  1030. ->findOneById($group_id))
  1031. || !($element = $this->getDoctrine()->getRepository('MuzichCoreBundle:Element')
  1032. ->findOneById($element_id)))
  1033. {
  1034. return $this->jsonNotFoundResponse();
  1035. }
  1036. if ($token != $this->getUser()->getPersonalHash('remove_from_group_'.$element->getId())
  1037. || $group->getOwner()->getId() != $this->getUserId())
  1038. {
  1039. return $this->jsonNotFoundResponse();
  1040. }
  1041. $element->setGroup(null);
  1042. $this->persist($element);
  1043. $this->flush();
  1044. return $this->jsonResponse(array(
  1045. 'status' => 'success'
  1046. ));
  1047. }
  1048. }