ElementController.php 34KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187
  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()->getEntityManager();
  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()->getEntityManager(),
  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()->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. // 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 (($response = $this->mustBeConnected()))
  318. {
  319. return $response;
  320. }
  321. if ($this->getRequest()->getMethod() != 'POST')
  322. {
  323. throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException();
  324. }
  325. /*
  326. * On met à jour l'ElementSearcher avec le form
  327. */
  328. $es = $this->getElementSearcher(null, true);
  329. $search_form = $this->getSearchForm($es);
  330. $search_form->bind($this->getRequest());
  331. if ($search_form->isValid())
  332. {
  333. $es->update($search_form->getData());
  334. }
  335. $es->update(array(
  336. // On veux de nouveaux éléments
  337. 'searchnew' => true,
  338. // Notre id de référence
  339. 'id_limit' => $refid,
  340. // On en veut qu'un certain nombres
  341. 'count' => $this->container->getParameter('search_default_count')
  342. ));
  343. // Récupération de ces nouveaux élméents
  344. $elements = $es->getElements($this->getDoctrine(), $this->getUserId());
  345. // On en fait un rendu graphique
  346. $html_elements = $this->render('MuzichCoreBundle:SearchElement:default.html.twig', array(
  347. 'user' => $this->getUser(),
  348. 'elements' => $elements
  349. ))->getContent();
  350. // On calcule le nouveau compte de nouveaux
  351. $count = 0;
  352. if (count($elements))
  353. {
  354. $es->update(array(
  355. // On veux de nouveaux éléments
  356. 'searchnew' => true,
  357. // Notre id de référence
  358. 'id_limit' => $elements[0]->getId(),
  359. // On n'en récupère que x
  360. 'count' => $this->container->getParameter('search_default_count')
  361. ));
  362. $count = $es->getElements($this->getDoctrine(), $this->getUserId(), 'count');
  363. }
  364. return $this->jsonResponse(array(
  365. 'status' => 'success',
  366. 'html' => $html_elements,
  367. 'count' => $count,
  368. 'message' => $this->getcountNewMessage($count)
  369. ));
  370. }
  371. /**
  372. * Action (ajax) ajoutant son vote "good" sur un élément
  373. *
  374. * @param int $element_id
  375. * @param string $token
  376. * @return Response
  377. */
  378. public function addVoteGoodAction($element_id, $token)
  379. {
  380. if (($non_condition = $this->userHaveNonConditionToMakeAction(SecurityContext::ACTION_ELEMENT_NOTE)) !== false)
  381. {
  382. return $this->jsonResponseError($non_condition);
  383. }
  384. if (!($element = $this->getDoctrine()->getRepository('MuzichCoreBundle:Element')
  385. ->findOneById($element_id)) || $this->getUser()->getPersonalHash($element_id) != $token)
  386. {
  387. return $this->jsonResponse(array(
  388. 'status' => 'error',
  389. 'errors' => array('NotFound')
  390. ));
  391. }
  392. if ($element->getOwner()->getId() == $this->getUserId())
  393. {
  394. return $this->jsonResponse(array(
  395. 'status' => 'error',
  396. 'errors' => array('NotAllowed')
  397. ));
  398. }
  399. // On ajoute un vote a l'élément
  400. $element->addVoteGood($this->getUser()->getId());
  401. // Puis on lance les actions propagés par ce vote
  402. $event = new EventElement($this->container);
  403. $event->onePointAdded($element);
  404. $this->getDoctrine()->getEntityManager()->persist($element);
  405. $this->getDoctrine()->getEntityManager()->flush();
  406. return $this->jsonResponse(array(
  407. 'status' => 'success',
  408. 'data' => array(
  409. 'a' => array(
  410. 'href' => $this->generateUrl('ajax_element_remove_vote_good', array(
  411. 'element_id' => $element->getId(),
  412. 'token' => $this->getUser()->getPersonalHash($element->getId())
  413. ))
  414. ),
  415. 'img' => array(
  416. 'src' => $this->getAssetUrl('/img/icon_thumb_red.png')
  417. ),
  418. 'element' => array(
  419. 'points' => $element->getPoints()
  420. )
  421. )
  422. ));
  423. }
  424. /**
  425. * Action (ajax) de retrait de son vote good
  426. *
  427. * @param int $element_id
  428. * @param string $token
  429. * @return Response
  430. */
  431. public function removeVoteGoodAction($element_id, $token)
  432. {
  433. if (($non_condition = $this->userHaveNonConditionToMakeAction(SecurityContext::ACTION_ELEMENT_NOTE)) !== false)
  434. {
  435. return $this->jsonResponseError($non_condition);
  436. }
  437. if (!($element = $this->getDoctrine()->getRepository('MuzichCoreBundle:Element')
  438. ->findOneById($element_id)) || $this->getUser()->getPersonalHash($element_id) != $token)
  439. {
  440. return $this->jsonResponse(array(
  441. 'status' => 'error',
  442. 'errors' => array('NotFound')
  443. ));
  444. }
  445. if ($element->getOwner()->getId() == $this->getUserId())
  446. {
  447. return $this->jsonResponse(array(
  448. 'status' => 'error',
  449. 'errors' => array('NotAllowed')
  450. ));
  451. }
  452. // Retrait du vote good
  453. $element->removeVoteGood($this->getUser()->getId());
  454. // Puis on lance les actions propagés par retrait de vote
  455. $event = new EventElement($this->container);
  456. $event->onePointRemoved($element);
  457. $this->getDoctrine()->getEntityManager()->persist($element);
  458. $this->getDoctrine()->getEntityManager()->flush();
  459. return $this->jsonResponse(array(
  460. 'status' => 'success',
  461. 'data' => array(
  462. 'a' => array(
  463. 'href' => $this->generateUrl('ajax_element_add_vote_good', array(
  464. 'element_id' => $element->getId(),
  465. 'token' => $this->getUser()->getPersonalHash($element->getId())
  466. ))
  467. ),
  468. 'img' => array(
  469. 'src' => $this->getAssetUrl('/img/icon_thumb.png')
  470. ),
  471. 'element' => array(
  472. 'points' => $element->getPoints()
  473. )
  474. )
  475. ));
  476. }
  477. /**
  478. * Retourne un json avec le form permettant a l'utilisateur de proposer des
  479. * tags sur un élément.
  480. *
  481. * @param int $element_id
  482. * @return Response
  483. */
  484. public function proposeTagsOpenAction($element_id)
  485. {
  486. if (($non_condition = $this->userHaveNonConditionToMakeAction(SecurityContext::ACTION_ELEMENT_TAGS_PROPOSITION)) !== false)
  487. {
  488. return $this->jsonResponseError($non_condition);
  489. }
  490. if (!($element = $this->getDoctrine()->getRepository('MuzichCoreBundle:Element')
  491. ->findOneById($element_id)))
  492. {
  493. return $this->jsonResponse(array(
  494. 'status' => 'error',
  495. 'errors' => array('NotFound')
  496. ));
  497. }
  498. $search_tags = array();
  499. foreach ($element->getTags() as $tag)
  500. {
  501. $search_tags[$tag->getId()] = $tag->getName();
  502. }
  503. $element->setTags($element->getTagsIdsJson());
  504. $form = $this->getAddForm($element, 'element_tag_proposition_'.$element->getId());
  505. $response = $this->render('MuzichCoreBundle:Element:tag.proposition.html.twig', array(
  506. 'form' => $form->createView(),
  507. 'form_name' => 'element_tag_proposition_'.$element->getId(),
  508. 'element_id' => $element->getId(),
  509. 'search_tags' => $search_tags
  510. ));
  511. return $this->jsonResponse(array(
  512. 'status' => 'success',
  513. 'form_name' => 'element_tag_proposition_'.$element->getId(),
  514. 'tags' => $search_tags,
  515. 'html' => $response->getContent()
  516. ));
  517. }
  518. public function proposeTagsProceedAction($element_id, $token)
  519. {
  520. if (($non_condition = $this->userHaveNonConditionToMakeAction(SecurityContext::ACTION_ELEMENT_TAGS_PROPOSITION)) !== false)
  521. {
  522. return $this->jsonResponseError($non_condition);
  523. }
  524. if (($response = $this->mustBeConnected(true)))
  525. {
  526. return $response;
  527. }
  528. if (!($element = $this->getDoctrine()->getRepository('MuzichCoreBundle:Element')
  529. ->findOneById($element_id)) || $token != $this->getUser()->getPersonalHash())
  530. {
  531. return $this->jsonResponse(array(
  532. 'status' => 'error',
  533. 'errors' => array('NotFound')
  534. ));
  535. }
  536. // On ne doit pas pouvoir proposer de tags sur son propre élément
  537. if ($element->getOwner()->getId() == $this->getUserId())
  538. {
  539. return $this->jsonResponse(array(
  540. 'status' => 'error',
  541. 'errors' => array('NotAllowed')
  542. ));
  543. }
  544. $values = $this->getRequest()->request->get('element_tag_proposition_'.$element->getId());
  545. $tags_ids = json_decode($values['tags'], true);
  546. $tags = array();
  547. if (count($tags_ids))
  548. {
  549. // On récupère les tags en base
  550. $tags = $this->getDoctrine()->getEntityManager()->getRepository('MuzichCoreBundle:Tag')
  551. ->getTagsWithIds($tags_ids)
  552. ;
  553. }
  554. if (!count($tags))
  555. {
  556. return $this->jsonResponse(array(
  557. 'status' => 'error',
  558. 'errors' => array($this->trans('element.tag_proposition.form.error.empty', array(), 'elements'))
  559. ));
  560. }
  561. /**
  562. * Bug lors des tests: L'user n'est pas 'lié' a celui en base par doctrine.
  563. * Docrine le voit si on faire une requete directe.
  564. */
  565. $user = $this->getUser();
  566. $proposition = new ElementTagsProposition();
  567. $proposition->setElement($element);
  568. $proposition->setUser($user);
  569. $date = new \DateTime(date('Y-m-d H:i:s'));
  570. $proposition->setCreated($date);
  571. foreach ($tags as $tag)
  572. {
  573. // Si le tag est a modérer, il faut que le propriétaire de l'élément
  574. // puisse voir ce tag, afin d'accepter en toute connaisance la proposition.
  575. if ($tag->getTomoderate())
  576. {
  577. if (!$tag->hasIdInPrivateIds($element->getOwner()->getId()))
  578. {
  579. // Si son id n'y est pas on la rajoute afin que le proprio puisse voir
  580. // ces nouveau tags
  581. $private_ids = json_decode($tag->getPrivateids(), true);
  582. $private_ids[] = $element->getOwner()->getId();
  583. $tag->setPrivateids(json_encode($private_ids));
  584. $this->getDoctrine()->getEntityManager()->persist($tag);
  585. }
  586. }
  587. $proposition->addTag($tag);
  588. }
  589. $element->setHasTagProposition(true);
  590. $this->getDoctrine()->getEntityManager()->persist($element);
  591. $this->getDoctrine()->getEntityManager()->persist($proposition);
  592. // Notifs etc
  593. $event = new EventElement($this->container);
  594. $event->tagsProposed($element);
  595. $this->getDoctrine()->getEntityManager()->flush();
  596. return $this->jsonResponse(array(
  597. 'status' => 'success',
  598. 'dom_id' => 'element_'.$element->getId()
  599. ));
  600. }
  601. public function proposedTagsViewAction($element_id)
  602. {
  603. if (($response = $this->mustBeConnected(true)))
  604. {
  605. return $response;
  606. }
  607. if (!($element = $this->getDoctrine()->getRepository('MuzichCoreBundle:Element')
  608. ->findOneById($element_id)))
  609. {
  610. return $this->jsonResponse(array(
  611. 'status' => 'error',
  612. 'errors' => array('NotFound')
  613. ));
  614. }
  615. if ($element->getOwner()->getId() != $this->getUserId())
  616. {
  617. return $this->jsonResponse(array(
  618. 'status' => 'error',
  619. 'errors' => array('NotAllowed')
  620. ));
  621. }
  622. // On récupére toute les propsotions pour cet élément
  623. $propositions = $this->getDoctrine()->getEntityManager()->getRepository('MuzichCoreBundle:ElementTagsProposition')
  624. ->findByElement($element->getId())
  625. ;
  626. $response = $this->render('MuzichCoreBundle:Element:tag.propositions.html.twig', array(
  627. 'propositions' => $propositions,
  628. 'element_id' => $element->getId()
  629. ));
  630. return $this->jsonResponse(array(
  631. 'status' => 'success',
  632. 'html' => $response->getContent()
  633. ));
  634. }
  635. public function proposedTagsAcceptAction($proposition_id, $token)
  636. {
  637. if (($response = $this->mustBeConnected(true)))
  638. {
  639. return $response;
  640. }
  641. if (!($proposition = $this->getDoctrine()->getRepository('MuzichCoreBundle:ElementTagsProposition')
  642. ->findOneById($proposition_id)) || $token != $this->getUser()->getPersonalHash($proposition_id))
  643. {
  644. return $this->jsonResponse(array(
  645. 'status' => 'error',
  646. 'errors' => array('NotFound')
  647. ));
  648. }
  649. // On commence par appliquer les nouveaux tags a l'élément
  650. $element = $proposition->getElement();
  651. $element->setTags(null);
  652. foreach ($proposition->getTags() as $tag)
  653. {
  654. $element->addTag($tag);
  655. }
  656. $element->setHasTagProposition(false);
  657. $element->setNeedTags(false);
  658. $this->getDoctrine()->getEntityManager()->persist($element);
  659. $event = new EventElement($this->container);
  660. $event->tagsAccepteds($proposition);
  661. $propositions = $this->getDoctrine()->getEntityManager()->getRepository('MuzichCoreBundle:ElementTagsProposition')
  662. ->findByElement($element->getId())
  663. ;
  664. // On supprime les proposition liés a cet élement
  665. foreach ($propositions as $proposition)
  666. {
  667. $this->getDoctrine()->getEntityManager()->remove($proposition);
  668. }
  669. // Traitement de l'Event si il y a
  670. $this->removeElementFromEvent($element->getId(), Event::TYPE_TAGS_PROPOSED);
  671. $this->getDoctrine()->getEntityManager()->flush();
  672. $element = $this->getDoctrine()->getRepository('MuzichCoreBundle:Element')
  673. ->findOneById($element->getId())
  674. ;
  675. // On récupère l'html de l'élément
  676. $html = $this->render('MuzichCoreBundle:SearchElement:element.html.twig', array(
  677. 'element' => $element
  678. ))->getContent();
  679. return $this->jsonResponse(array(
  680. 'status' => 'success',
  681. 'html' => $html
  682. ));
  683. }
  684. public function proposedTagsRefuseAction($element_id, $token)
  685. {
  686. if (($response = $this->mustBeConnected(true)))
  687. {
  688. return $response;
  689. }
  690. if (!($element = $this->getDoctrine()->getRepository('MuzichCoreBundle:Element')
  691. ->findOneById($element_id)) || $token != $this->getUser()->getPersonalHash($element_id))
  692. {
  693. return $this->jsonResponse(array(
  694. 'status' => 'error',
  695. 'errors' => array('NotFound')
  696. ));
  697. }
  698. // On supprime les proposition liés a cet élement
  699. $propositions = $this->getDoctrine()->getEntityManager()->getRepository('MuzichCoreBundle:ElementTagsProposition')
  700. ->findByElement($element->getId())
  701. ;
  702. foreach ($propositions as $proposition)
  703. {
  704. $this->getDoctrine()->getEntityManager()->remove($proposition);
  705. }
  706. // Traitement de l'Event si il y a
  707. $this->removeElementFromEvent($element->getId(), Event::TYPE_TAGS_PROPOSED);
  708. // On spécifie qu'il n'y as plus de proposition
  709. $element->setHasTagProposition(false);
  710. $this->getDoctrine()->getEntityManager()->persist($element);
  711. $this->getDoctrine()->getEntityManager()->flush();
  712. return $this->jsonResponse(array(
  713. 'status' => 'success'
  714. ));
  715. }
  716. protected function removeElementFromEvent($element_id, $event_type)
  717. {
  718. if (($event = $this->getEntityManager()->getRepository('MuzichCoreBundle:Event')
  719. ->findUserEventWithElementId($this->getUserId(), $element_id, $event_type)))
  720. {
  721. $event->removeId($element_id);
  722. if (!$event->getCount())
  723. {
  724. $this->remove($event);
  725. $this->flush();
  726. return;
  727. }
  728. $this->persist($event);
  729. $this->flush();
  730. }
  731. }
  732. public function reshareAction(Request $request, $element_id, $token)
  733. {
  734. if (($response = $this->mustBeConnected(true)))
  735. {
  736. return $response;
  737. }
  738. if ($this->getUser()->getPersonalHash('reshare_'.$element_id) != $token)
  739. {
  740. throw new \Symfony\Component\HttpFoundation\File\Exception\AccessDeniedException();
  741. }
  742. if (!($element = $this->getDoctrine()->getRepository('MuzichCoreBundle:Element')
  743. ->findOneById($element_id)))
  744. {
  745. throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException();
  746. }
  747. if ($element->getOwner()->getId() == $this->getUserId())
  748. {
  749. throw new \Symfony\Component\HttpFoundation\File\Exception\AccessDeniedException();
  750. }
  751. /**
  752. * Bug lors des tests: L'user n'est pas 'lié' a celui en base par doctrine.
  753. * Docrine le voit si on faire une requete directe.
  754. */
  755. $user = $this->getUser();
  756. // Pour le repartage on crée un nouvel élément
  757. $element_reshared = new Element();
  758. $element_reshared->setUrl($element->getUrl());
  759. $element_reshared->setName($element->getName());
  760. $element_reshared->addTags($element->getTags());
  761. $element_reshared->setParent($element);
  762. // On utilise le gestionnaire d'élément
  763. $factory = new ElementManager($element_reshared, $this->getEntityManager(), $this->container);
  764. $factory->proceedFill($user, false);
  765. // On se retrouve maintenant avec un nouvel element tout neuf
  766. $this->persist($element_reshared);
  767. $this->flush();
  768. $html_element = $this->render('MuzichCoreBundle:SearchElement:li.element.html.twig', array(
  769. 'element' => $element_reshared,
  770. 'class_color' => 'odd' // TODO: n'est plus utilisé
  771. ))->getContent();
  772. return $this->jsonResponse(array(
  773. 'status' => 'success',
  774. 'html' => $html_element,
  775. 'groups' => $this->isAddedElementCanBeInGroup($element_reshared)
  776. ));
  777. }
  778. protected function findTagsWithProposeds($tags)
  779. {
  780. $tag_like = new TagLike($this->getDoctrine()->getEntityManager());
  781. $tags_with_likes = array();
  782. foreach ($tags as $tag_name)
  783. {
  784. // On va determiner si on connais ces tags
  785. $tag_like_tag = $tag_like->getSimilarTags($tag_name, $this->getUserId(true));
  786. // Premièrement: Si on a trouvé des équivalents en base
  787. if (array_key_exists('tags', $tag_like_tag))
  788. {
  789. if (count($tag_like_tag['tags']))
  790. {
  791. // Deuxièmement: Si nos algorythmes on déterminés qu'on l'a en base
  792. if ($tag_like_tag['same_found'])
  793. {
  794. // A ce moment là on le considère comme "bon"
  795. // Et on prend le premier
  796. $tags_with_likes[] = array(
  797. 'original_name' => $tag_name,
  798. 'like_found' => true,
  799. 'like' => $tag_like_tag['tags'][0]
  800. );
  801. }
  802. // On considère ce tag comme inconnu, l'utilisateur peut toute fois
  803. // l'ajouté a notre base.
  804. else
  805. {
  806. $tags_with_likes[] = array(
  807. 'original_name' => $tag_name,
  808. 'like_found' => false,
  809. 'like' => array()
  810. );
  811. }
  812. }
  813. }
  814. }
  815. return $tags_with_likes;
  816. }
  817. public function getDatasApiAction(Request $request)
  818. {
  819. $url = null;
  820. if (count(($element_add_values = $request->get('element_add'))))
  821. {
  822. $url = trim($element_add_values['url']);
  823. }
  824. // On vérifie la tête de l'url quand même
  825. if (filter_var($url, FILTER_VALIDATE_URL) === false)
  826. {
  827. return $this->jsonResponse(array(
  828. 'status' => 'error',
  829. 'errors' => array(
  830. $this->trans('error.url.invalid', array(), 'validators')
  831. )
  832. ));
  833. }
  834. // On construit l'élèment qui va nous permettre de travailler avec l'api
  835. $element = new Element();
  836. $element->setUrl($url);
  837. $factory = new ElementManager($element, $this->getEntityManager(), $this->container);
  838. $factory->proceedFill((!$this->isVisitor())?$this->getUser():null);
  839. // On gère les tags proposés
  840. $tags_propositions = array();
  841. if (count($tags = $element->getProposedTags()))
  842. {
  843. $tags_propositions = $this->findTagsWithProposeds($tags);
  844. }
  845. return $this->jsonResponse(array(
  846. 'status' => 'success',
  847. 'name' => $element->getProposedName(),
  848. 'tags' => $tags_propositions,
  849. 'thumb' => $element->getThumbnailUrl()
  850. ));
  851. }
  852. /**
  853. * Retourne les données permettant de faire une playlist
  854. *
  855. * @param Request $request
  856. * @param "filter"|"show"|"favorites" $type
  857. * @param ~ $data
  858. */
  859. public function getDatasAutoplayAction(Request $request, $element_id, $type, $data, $show_type = null, $show_id = null)
  860. {
  861. $elements = array();
  862. $elements_json = array();
  863. if ($type == 'filter')
  864. {
  865. // Pour cette option on utilise le dernier filtre appliqué
  866. $search_object = $this->getElementSearcher();
  867. $search_object->update(array(
  868. 'count' => $this->container->getParameter('autoplay_max_elements'),
  869. 'id_limit' => $element_id+1
  870. ));
  871. $elements = $search_object->getElements($this->getDoctrine(), $this->getUserId(true));
  872. }
  873. elseif ($type == 'show')
  874. {
  875. if ($show_type != 'user' && $show_type != 'group')
  876. {
  877. throw $this->createNotFoundException('Not found');
  878. }
  879. $tags = null;
  880. $tag_ids = json_decode($data);
  881. $search_object = new ElementSearcher();
  882. if (count($tag_ids))
  883. {
  884. $tags = array();
  885. foreach ($tag_ids as $id)
  886. {
  887. $tags[$id] = $id;
  888. }
  889. }
  890. $search_object->init(array(
  891. 'tags' => $tags,
  892. $show_type.'_id' => $show_id,
  893. 'count' => $this->container->getParameter('autoplay_max_elements'),
  894. 'id_limit' => $element_id+1
  895. ));
  896. $elements = $search_object->getElements($this->getDoctrine(), $this->getUserId(true));
  897. }
  898. elseif ($type == 'favorite')
  899. {
  900. $tags = null;
  901. $tag_ids = json_decode($data);
  902. $search_object = new ElementSearcher();
  903. if (count($tag_ids))
  904. {
  905. $tags = array();
  906. foreach ($tag_ids as $id)
  907. {
  908. $tags[$id] = $id;
  909. }
  910. }
  911. $search_object->init(array(
  912. 'tags' => $tags,
  913. 'user_id' => $show_id,
  914. 'favorite' => true,
  915. 'count' => $this->container->getParameter('autoplay_max_elements'),
  916. 'id_limit' => $element_id+1
  917. ));
  918. $elements = $search_object->getElements($this->getDoctrine(), $this->getUserId(true));
  919. }
  920. if (count($elements))
  921. {
  922. // On récupère les élements
  923. $autoplaym = new AutoplayManager($elements, $this->container);
  924. $elements_json = $autoplaym->getList();
  925. }
  926. return $this->jsonResponse(array(
  927. 'status' => 'success',
  928. 'data' => $elements_json
  929. ));
  930. }
  931. public function getOneDomAction(Request $request, $element_id, $type)
  932. {
  933. if (!in_array($type, array('autoplay')))
  934. {
  935. return $this->jsonResponse(array(
  936. 'status' => 'error',
  937. 'errors' => array('NotAllowed')
  938. ));
  939. }
  940. // variables pour le template
  941. $display_edit_actions = true;
  942. $display_player = true;
  943. $display_comments = true;
  944. if ($type == 'autoplay')
  945. {
  946. $display_edit_actions = false;
  947. $display_player = false;
  948. $display_comments = false;
  949. }
  950. // On prépare la récupèration de l'élèment
  951. $es = new ElementSearcher();
  952. $es->init(array(
  953. 'ids' => array($element_id)
  954. ));
  955. if (!($element = $es->getElements($this->getDoctrine(), $this->getUserId(true), 'single')))
  956. {
  957. throw $this->createNotFoundException('Not found');
  958. }
  959. $html = $this->render('MuzichCoreBundle:SearchElement:element.html.twig', array(
  960. 'element' => $element,
  961. 'display_edit_actions' => $display_edit_actions,
  962. 'display_player' => $display_player,
  963. 'display_comments' => $display_comments
  964. ))->getContent();
  965. return $this->jsonResponse(array(
  966. 'status' => 'success',
  967. 'data' => $html
  968. ));
  969. }
  970. public function geJamendotStreamDatasAction(Request $request, $element_id)
  971. {
  972. if (!($element = $this->getDoctrine()->getRepository('MuzichCoreBundle:Element')
  973. ->findOneById($element_id)))
  974. {
  975. throw $this->createNotFoundException('Not found');
  976. }
  977. $manager = new ElementManager($element, $this->getEntityManager(), $this->container);
  978. $stream_data = $manager->getFactory()->getStreamData();
  979. return $this->jsonResponse(array(
  980. 'status' => 'success',
  981. 'data' => $stream_data,
  982. ));
  983. }
  984. public function getEmbedCodeAction($element_id)
  985. {
  986. if (!$element_id)
  987. {
  988. return $this->jsonNotFoundResponse();
  989. }
  990. if (!($element = $this->getDoctrine()->getRepository('MuzichCoreBundle:Element')
  991. ->findOneById($element_id)))
  992. {
  993. return $this->jsonNotFoundResponse();
  994. }
  995. return $this->jsonResponse(array(
  996. 'status' => 'success',
  997. 'data' => $element->getEmbed(),
  998. ));
  999. }
  1000. public function removeFromGroupAction($group_id, $element_id, $token)
  1001. {
  1002. if (!($group = $this->getDoctrine()->getRepository('MuzichCoreBundle:Group')
  1003. ->findOneById($group_id))
  1004. || !($element = $this->getDoctrine()->getRepository('MuzichCoreBundle:Element')
  1005. ->findOneById($element_id)))
  1006. {
  1007. return $this->jsonNotFoundResponse();
  1008. }
  1009. if ($token != $this->getUser()->getPersonalHash('remove_from_group_'.$element->getId())
  1010. || $group->getOwner()->getId() != $this->getUserId())
  1011. {
  1012. return $this->jsonNotFoundResponse();
  1013. }
  1014. $element->setGroup(null);
  1015. $this->persist($element);
  1016. $this->flush();
  1017. return $this->jsonResponse(array(
  1018. 'status' => 'success'
  1019. ));
  1020. }
  1021. }