ElementController.php 35KB

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