ElementController.php 33KB

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