ElementController.php 35KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224
  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. 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. 'display_privates' => true
  933. ));
  934. if (!($element = $es->getElements($this->getDoctrine(), $this->getUserId(true), 'single')))
  935. {
  936. return $this->jsonResponse(array(
  937. self::RESPONSE_STATUS_ID => self::RESPONSE_STATUS_ERROR,
  938. self::RESPONSE_ERROR_ID => self::ERROR_TYPE_NOTFOUND,
  939. self::RESPONSE_MESSAGE_ID => $this->trans('noelements.nofound_anymore', array(), 'elements')
  940. ));
  941. }
  942. $html = $this->render('MuzichCoreBundle:SearchElement:li.element.html.twig', array(
  943. 'element' => $element,
  944. 'display_edit_actions' => false,
  945. 'display_player' => true,
  946. 'display_comments' => true
  947. ))->getContent();
  948. return $this->jsonResponse(array(
  949. 'status' => 'success',
  950. 'data' => $html
  951. ));
  952. }
  953. public function getOneDomAction(Request $request, $element_id, $type)
  954. {
  955. if (!in_array($type, array('autoplay')) || !$element_id)
  956. {
  957. return $this->jsonResponse(array(
  958. 'status' => 'error'
  959. ));
  960. }
  961. // variables pour le template
  962. $display_edit_actions = true;
  963. $display_player = true;
  964. $display_comments = true;
  965. if ($type == 'autoplay')
  966. {
  967. $display_edit_actions = false;
  968. $display_player = false;
  969. $display_comments = false;
  970. }
  971. // On prépare la récupèration de l'élèment
  972. $es = new ElementSearcher();
  973. $es->init(array(
  974. 'ids' => array($element_id),
  975. 'display_privates' => true
  976. ));
  977. if (!($element = $es->getElements($this->getDoctrine(), $this->getUserId(true), 'single')))
  978. {
  979. throw $this->createNotFoundException('Not found');
  980. }
  981. $html = $this->render('MuzichCoreBundle:SearchElement:element.html.twig', array(
  982. 'element' => $element,
  983. 'display_edit_actions' => $display_edit_actions,
  984. 'display_player' => $display_player,
  985. 'display_comments' => $display_comments
  986. ))->getContent();
  987. return $this->jsonResponse(array(
  988. 'status' => 'success',
  989. 'data' => $html
  990. ));
  991. }
  992. public function geJamendotStreamDatasAction(Request $request, $element_id)
  993. {
  994. if (!($element = $this->getDoctrine()->getRepository('MuzichCoreBundle:Element')
  995. ->findOneById($element_id)))
  996. {
  997. throw $this->createNotFoundException('Not found');
  998. }
  999. $manager = new ElementManager($element, $this->getEntityManager(), $this->container);
  1000. $stream_data = $manager->getFactory()->getStreamData();
  1001. return $this->jsonResponse(array(
  1002. 'status' => 'success',
  1003. 'data' => $stream_data,
  1004. ));
  1005. }
  1006. public function getEmbedCodeAction($element_id)
  1007. {
  1008. if (!$element_id)
  1009. {
  1010. return $this->jsonNotFoundResponse();
  1011. }
  1012. if (!($element = $this->getDoctrine()->getRepository('MuzichCoreBundle:Element')
  1013. ->findOneById($element_id)))
  1014. {
  1015. return $this->jsonNotFoundResponse();
  1016. }
  1017. return $this->jsonResponse(array(
  1018. 'status' => 'success',
  1019. 'data' => $element->getEmbed(),
  1020. ));
  1021. }
  1022. public function removeFromGroupAction($group_id, $element_id, $token)
  1023. {
  1024. if (!($group = $this->getDoctrine()->getRepository('MuzichCoreBundle:Group')
  1025. ->findOneById($group_id))
  1026. || !($element = $this->getDoctrine()->getRepository('MuzichCoreBundle:Element')
  1027. ->findOneById($element_id)))
  1028. {
  1029. return $this->jsonNotFoundResponse();
  1030. }
  1031. if ($token != $this->getUser()->getPersonalHash('remove_from_group_'.$element->getId())
  1032. || $group->getOwner()->getId() != $this->getUserId())
  1033. {
  1034. return $this->jsonNotFoundResponse();
  1035. }
  1036. $element->setGroup(null);
  1037. $this->persist($element);
  1038. $this->flush();
  1039. return $this->jsonResponse(array(
  1040. 'status' => 'success'
  1041. ));
  1042. }
  1043. public function shareFromAction(Request $request)
  1044. {
  1045. if (!$request->get('from_url'))
  1046. throw $this->createNotFoundException();
  1047. return $this->render('MuzichCoreBundle:Element:share_from.html.twig', array(
  1048. 'add_form' => $this->getAddForm()->createView(),
  1049. 'from_url' => $request->get('from_url')
  1050. ));
  1051. }
  1052. }