ElementController.php 35KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209
  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 ($this->getRequest()->getMethod() != 'POST')
  318. {
  319. throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException();
  320. }
  321. /*
  322. * On met à jour l'ElementSearcher avec le form
  323. */
  324. $es = $this->getElementSearcher(null, true);
  325. $search_form = $this->getSearchForm($es);
  326. $search_form->bind($this->getRequest());
  327. if ($search_form->isValid())
  328. {
  329. $es->update($search_form->getData());
  330. }
  331. $es->update(array(
  332. // On veux de nouveaux éléments
  333. 'searchnew' => true,
  334. // Notre id de référence
  335. 'id_limit' => $refid,
  336. // On en veut qu'un certain nombres
  337. 'count' => $this->container->getParameter('search_default_count')
  338. ));
  339. // Récupération de ces nouveaux élméents
  340. $elements = $es->getElements($this->getDoctrine(), $this->getUserId(true));
  341. // On en fait un rendu graphique
  342. $html_elements = $this->render('MuzichCoreBundle:SearchElement:default.html.twig', array(
  343. 'user' => $this->getUser(),
  344. 'elements' => $elements
  345. ))->getContent();
  346. // On calcule le nouveau compte de nouveaux
  347. $count = 0;
  348. if (count($elements))
  349. {
  350. $es->update(array(
  351. // On veux de nouveaux éléments
  352. 'searchnew' => true,
  353. // Notre id de référence
  354. 'id_limit' => $elements[0]->getId(),
  355. // On n'en récupère que x
  356. 'count' => $this->container->getParameter('search_default_count')
  357. ));
  358. $count = $es->getElements($this->getDoctrine(), $this->getUserId(true), 'count');
  359. }
  360. return $this->jsonResponse(array(
  361. 'status' => 'success',
  362. 'html' => $html_elements,
  363. 'count' => $count,
  364. 'message' => $this->getcountNewMessage($count)
  365. ));
  366. }
  367. /**
  368. * Action (ajax) ajoutant son vote "good" sur un élément
  369. *
  370. * @param int $element_id
  371. * @param string $token
  372. * @return Response
  373. */
  374. public function addVoteGoodAction($element_id, $token)
  375. {
  376. if (($non_condition = $this->userHaveNonConditionToMakeAction(SecurityContext::ACTION_ELEMENT_NOTE)) !== false)
  377. {
  378. return $this->jsonResponseError($non_condition);
  379. }
  380. if (!($element = $this->getDoctrine()->getRepository('MuzichCoreBundle:Element')
  381. ->findOneById($element_id)) || $this->getUser()->getPersonalHash($element_id) != $token)
  382. {
  383. return $this->jsonResponse(array(
  384. 'status' => 'error',
  385. 'errors' => array('NotFound')
  386. ));
  387. }
  388. if ($element->getOwner()->getId() == $this->getUserId())
  389. {
  390. return $this->jsonResponse(array(
  391. 'status' => 'error',
  392. 'errors' => array('NotAllowed')
  393. ));
  394. }
  395. // On ajoute un vote a l'élément
  396. $element->addVoteGood($this->getUser()->getId());
  397. // Puis on lance les actions propagés par ce vote
  398. $event = new EventElement($this->container);
  399. $event->onePointAdded($element);
  400. $this->getDoctrine()->getEntityManager()->persist($element);
  401. $this->getDoctrine()->getEntityManager()->flush();
  402. return $this->jsonResponse(array(
  403. 'status' => 'success',
  404. 'data' => array(
  405. 'a' => array(
  406. 'href' => $this->generateUrl('ajax_element_remove_vote_good', array(
  407. 'element_id' => $element->getId(),
  408. 'token' => $this->getUser()->getPersonalHash($element->getId())
  409. ))
  410. ),
  411. 'img' => array(
  412. 'src' => $this->getAssetUrl('/img/icon_thumb_red.png')
  413. ),
  414. 'element' => array(
  415. 'points' => $element->getPoints()
  416. )
  417. )
  418. ));
  419. }
  420. /**
  421. * Action (ajax) de retrait de son vote good
  422. *
  423. * @param int $element_id
  424. * @param string $token
  425. * @return Response
  426. */
  427. public function removeVoteGoodAction($element_id, $token)
  428. {
  429. if (($non_condition = $this->userHaveNonConditionToMakeAction(SecurityContext::ACTION_ELEMENT_NOTE)) !== false)
  430. {
  431. return $this->jsonResponseError($non_condition);
  432. }
  433. if (!($element = $this->getDoctrine()->getRepository('MuzichCoreBundle:Element')
  434. ->findOneById($element_id)) || $this->getUser()->getPersonalHash($element_id) != $token)
  435. {
  436. return $this->jsonResponse(array(
  437. 'status' => 'error',
  438. 'errors' => array('NotFound')
  439. ));
  440. }
  441. if ($element->getOwner()->getId() == $this->getUserId())
  442. {
  443. return $this->jsonResponse(array(
  444. 'status' => 'error',
  445. 'errors' => array('NotAllowed')
  446. ));
  447. }
  448. // Retrait du vote good
  449. $element->removeVoteGood($this->getUser()->getId());
  450. // Puis on lance les actions propagés par retrait de vote
  451. $event = new EventElement($this->container);
  452. $event->onePointRemoved($element);
  453. $this->getDoctrine()->getEntityManager()->persist($element);
  454. $this->getDoctrine()->getEntityManager()->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()->getEntityManager()->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()->getEntityManager()->persist($tag);
  581. }
  582. }
  583. $proposition->addTag($tag);
  584. }
  585. $element->setHasTagProposition(true);
  586. $this->getDoctrine()->getEntityManager()->persist($element);
  587. $this->getDoctrine()->getEntityManager()->persist($proposition);
  588. // Notifs etc
  589. $event = new EventElement($this->container);
  590. $event->tagsProposed($element);
  591. $this->getDoctrine()->getEntityManager()->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()->getEntityManager()->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()->getEntityManager()->persist($element);
  655. $event = new EventElement($this->container);
  656. $event->tagsAccepteds($proposition);
  657. $propositions = $this->getDoctrine()->getEntityManager()->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()->getEntityManager()->remove($proposition);
  664. }
  665. // Traitement de l'Event si il y a
  666. $this->removeElementFromEvent($element->getId(), Event::TYPE_TAGS_PROPOSED);
  667. $this->getDoctrine()->getEntityManager()->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()->getEntityManager()->getRepository('MuzichCoreBundle:ElementTagsProposition')
  696. ->findByElement($element->getId())
  697. ;
  698. foreach ($propositions as $proposition)
  699. {
  700. $this->getDoctrine()->getEntityManager()->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()->getEntityManager()->persist($element);
  707. $this->getDoctrine()->getEntityManager()->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()->getEntityManager());
  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. if (count($tag_ids))
  879. {
  880. $tags = array();
  881. foreach ($tag_ids as $id)
  882. {
  883. $tags[$id] = $id;
  884. }
  885. }
  886. $search_object->init(array(
  887. 'tags' => $tags,
  888. $show_type.'_id' => $show_id,
  889. 'count' => $this->container->getParameter('autoplay_max_elements'),
  890. 'id_limit' => $element_id+1
  891. ));
  892. $elements = $search_object->getElements($this->getDoctrine(), $this->getUserId(true));
  893. }
  894. elseif ($type == 'favorite')
  895. {
  896. $tags = null;
  897. $tag_ids = json_decode($data);
  898. $search_object = new ElementSearcher();
  899. if (count($tag_ids))
  900. {
  901. $tags = array();
  902. foreach ($tag_ids as $id)
  903. {
  904. $tags[$id] = $id;
  905. }
  906. }
  907. $search_object->init(array(
  908. 'tags' => $tags,
  909. 'user_id' => $show_id,
  910. 'favorite' => true,
  911. 'count' => $this->container->getParameter('autoplay_max_elements'),
  912. 'id_limit' => $element_id+1
  913. ));
  914. $elements = $search_object->getElements($this->getDoctrine(), $this->getUserId(true));
  915. }
  916. if (count($elements))
  917. {
  918. // On récupère les élements
  919. $autoplaym = new AutoplayManager($elements, $this->container);
  920. $elements_json = $autoplaym->getList();
  921. }
  922. return $this->jsonResponse(array(
  923. 'status' => 'success',
  924. 'data' => $elements_json
  925. ));
  926. }
  927. public function getOneAction($element_id)
  928. {
  929. $es = new ElementSearcher();
  930. $es->init(array(
  931. 'ids' => array($element_id)
  932. ));
  933. if (!($element = $es->getElements($this->getDoctrine(), $this->getUserId(true), 'single')))
  934. {
  935. return $this->jsonResponse(array(
  936. 'status' => 'error'
  937. ));
  938. }
  939. $html = $this->render('MuzichCoreBundle:SearchElement:li.element.html.twig', array(
  940. 'element' => $element,
  941. 'display_edit_actions' => false,
  942. 'display_player' => true,
  943. 'display_comments' => true
  944. ))->getContent();
  945. return $this->jsonResponse(array(
  946. 'status' => 'success',
  947. 'data' => $html
  948. ));
  949. }
  950. public function getOneDomAction(Request $request, $element_id, $type)
  951. {
  952. if (!in_array($type, array('autoplay')) || !$element_id)
  953. {
  954. return $this->jsonResponse(array(
  955. 'status' => 'error'
  956. ));
  957. }
  958. // variables pour le template
  959. $display_edit_actions = true;
  960. $display_player = true;
  961. $display_comments = true;
  962. if ($type == 'autoplay')
  963. {
  964. $display_edit_actions = false;
  965. $display_player = false;
  966. $display_comments = false;
  967. }
  968. // On prépare la récupèration de l'élèment
  969. $es = new ElementSearcher();
  970. $es->init(array(
  971. 'ids' => array($element_id)
  972. ));
  973. if (!($element = $es->getElements($this->getDoctrine(), $this->getUserId(true), 'single')))
  974. {
  975. throw $this->createNotFoundException('Not found');
  976. }
  977. $html = $this->render('MuzichCoreBundle:SearchElement:element.html.twig', array(
  978. 'element' => $element,
  979. 'display_edit_actions' => $display_edit_actions,
  980. 'display_player' => $display_player,
  981. 'display_comments' => $display_comments
  982. ))->getContent();
  983. return $this->jsonResponse(array(
  984. 'status' => 'success',
  985. 'data' => $html
  986. ));
  987. }
  988. public function geJamendotStreamDatasAction(Request $request, $element_id)
  989. {
  990. if (!($element = $this->getDoctrine()->getRepository('MuzichCoreBundle:Element')
  991. ->findOneById($element_id)))
  992. {
  993. throw $this->createNotFoundException('Not found');
  994. }
  995. $manager = new ElementManager($element, $this->getEntityManager(), $this->container);
  996. $stream_data = $manager->getFactory()->getStreamData();
  997. return $this->jsonResponse(array(
  998. 'status' => 'success',
  999. 'data' => $stream_data,
  1000. ));
  1001. }
  1002. public function getEmbedCodeAction($element_id)
  1003. {
  1004. if (!$element_id)
  1005. {
  1006. return $this->jsonNotFoundResponse();
  1007. }
  1008. if (!($element = $this->getDoctrine()->getRepository('MuzichCoreBundle:Element')
  1009. ->findOneById($element_id)))
  1010. {
  1011. return $this->jsonNotFoundResponse();
  1012. }
  1013. return $this->jsonResponse(array(
  1014. 'status' => 'success',
  1015. 'data' => $element->getEmbed(),
  1016. ));
  1017. }
  1018. public function removeFromGroupAction($group_id, $element_id, $token)
  1019. {
  1020. if (!($group = $this->getDoctrine()->getRepository('MuzichCoreBundle:Group')
  1021. ->findOneById($group_id))
  1022. || !($element = $this->getDoctrine()->getRepository('MuzichCoreBundle:Element')
  1023. ->findOneById($element_id)))
  1024. {
  1025. return $this->jsonNotFoundResponse();
  1026. }
  1027. if ($token != $this->getUser()->getPersonalHash('remove_from_group_'.$element->getId())
  1028. || $group->getOwner()->getId() != $this->getUserId())
  1029. {
  1030. return $this->jsonNotFoundResponse();
  1031. }
  1032. $element->setGroup(null);
  1033. $this->persist($element);
  1034. $this->flush();
  1035. return $this->jsonResponse(array(
  1036. 'status' => 'success'
  1037. ));
  1038. }
  1039. }