ElementController.php 35KB

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