ElementController.php 36KB

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