ElementController.php 35KB

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