CRUDController.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864
  1. <?php
  2. /*
  3. * This file is part of the Sonata package.
  4. *
  5. * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Sonata\AdminBundle\Controller;
  11. use Symfony\Component\HttpFoundation\RedirectResponse;
  12. use Symfony\Component\HttpFoundation\Response;
  13. use Symfony\Component\HttpKernel\Exception\HttpException;
  14. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  15. use Symfony\Component\Security\Core\Exception\AccessDeniedException;
  16. use Symfony\Component\DependencyInjection\ContainerInterface;
  17. use Symfony\Bundle\FrameworkBundle\Controller\Controller;
  18. use Sonata\AdminBundle\Exception\ModelManagerException;
  19. use Symfony\Component\HttpFoundation\Request;
  20. use Sonata\AdminBundle\Datagrid\ProxyQueryInterface;
  21. use Sonata\AdminBundle\Admin\BaseFieldDescription;
  22. use Sonata\AdminBundle\Util\AdminObjectAclData;
  23. class CRUDController extends Controller
  24. {
  25. /**
  26. * The related Admin class
  27. *
  28. * @var \Sonata\AdminBundle\Admin\AdminInterface
  29. */
  30. protected $admin;
  31. /**
  32. * @param mixed $data
  33. * @param integer $status
  34. * @param array $headers
  35. *
  36. * @return Response with json encoded data
  37. */
  38. public function renderJson($data, $status = 200, $headers = array())
  39. {
  40. // fake content-type so browser does not show the download popup when this
  41. // response is rendered through an iframe (used by the jquery.form.js plugin)
  42. // => don't know yet if it is the best solution
  43. if ($this->get('request')->get('_xml_http_request')
  44. && strpos($this->get('request')->headers->get('Content-Type'), 'multipart/form-data') === 0) {
  45. $headers['Content-Type'] = 'text/plain';
  46. } else {
  47. $headers['Content-Type'] = 'application/json';
  48. }
  49. return new Response(json_encode($data), $status, $headers);
  50. }
  51. /**
  52. *
  53. * @return boolean true if the request is done by an ajax like query
  54. */
  55. public function isXmlHttpRequest()
  56. {
  57. return $this->get('request')->isXmlHttpRequest() || $this->get('request')->get('_xml_http_request');
  58. }
  59. /**
  60. * Returns the correct RESTful verb, given either by the request itself or
  61. * via the "_method" parameter.
  62. *
  63. * @return string HTTP method, either
  64. */
  65. protected function getRestMethod()
  66. {
  67. $request = $this->getRequest();
  68. if (Request::getHttpMethodParameterOverride() || !$request->request->has('_method')) {
  69. return $request->getMethod();
  70. }
  71. return $request->request->get('_method');
  72. }
  73. /**
  74. * Sets the Container associated with this Controller.
  75. *
  76. * @param ContainerInterface $container A ContainerInterface instance
  77. */
  78. public function setContainer(ContainerInterface $container = null)
  79. {
  80. $this->container = $container;
  81. $this->configure();
  82. }
  83. /**
  84. * Contextualize the admin class depends on the current request
  85. *
  86. * @throws \RuntimeException
  87. * @return void
  88. */
  89. public function configure()
  90. {
  91. $adminCode = $this->container->get('request')->get('_sonata_admin');
  92. if (!$adminCode) {
  93. throw new \RuntimeException(sprintf('There is no `_sonata_admin` defined for the controller `%s` and the current route `%s`', get_class($this), $this->container->get('request')->get('_route')));
  94. }
  95. $this->admin = $this->container->get('sonata.admin.pool')->getAdminByAdminCode($adminCode);
  96. if (!$this->admin) {
  97. throw new \RuntimeException(sprintf('Unable to find the admin class related to the current controller (%s)', get_class($this)));
  98. }
  99. $rootAdmin = $this->admin;
  100. if ($this->admin->isChild()) {
  101. $this->admin->setCurrentChild(true);
  102. $rootAdmin = $rootAdmin->getParent();
  103. }
  104. $request = $this->container->get('request');
  105. $rootAdmin->setRequest($request);
  106. if ($request->get('uniqid')) {
  107. $this->admin->setUniqid($request->get('uniqid'));
  108. }
  109. }
  110. /**
  111. * return the base template name
  112. *
  113. * @return string the template name
  114. */
  115. public function getBaseTemplate()
  116. {
  117. if ($this->isXmlHttpRequest()) {
  118. return $this->admin->getTemplate('ajax');
  119. }
  120. return $this->admin->getTemplate('layout');
  121. }
  122. /**
  123. * @param string $view
  124. * @param array $parameters
  125. * @param Response $response
  126. *
  127. * @return Response
  128. */
  129. public function render($view, array $parameters = array(), Response $response = null)
  130. {
  131. $parameters['admin'] = isset($parameters['admin']) ? $parameters['admin'] : $this->admin;
  132. $parameters['base_template'] = isset($parameters['base_template']) ? $parameters['base_template'] : $this->getBaseTemplate();
  133. $parameters['admin_pool'] = $this->get('sonata.admin.pool');
  134. return parent::render($view, $parameters, $response);
  135. }
  136. /**
  137. * return the Response object associated to the list action
  138. *
  139. * @throws \Symfony\Component\Security\Core\Exception\AccessDeniedException
  140. *
  141. * @return Response
  142. */
  143. public function listAction()
  144. {
  145. if (false === $this->admin->isGranted('LIST')) {
  146. throw new AccessDeniedException();
  147. }
  148. $datagrid = $this->admin->getDatagrid();
  149. $formView = $datagrid->getForm()->createView();
  150. // set the theme for the current Admin Form
  151. $this->get('twig')->getExtension('form')->renderer->setTheme($formView, $this->admin->getFilterTheme());
  152. return $this->render($this->admin->getTemplate('list'), array(
  153. 'action' => 'list',
  154. 'form' => $formView,
  155. 'datagrid' => $datagrid,
  156. 'csrf_token' => $this->getCsrfToken('sonata.batch'),
  157. ));
  158. }
  159. /**
  160. * execute a batch delete
  161. *
  162. * @throws \Symfony\Component\Security\Core\Exception\AccessDeniedException
  163. *
  164. * @param \Sonata\AdminBundle\Datagrid\ProxyQueryInterface $query
  165. *
  166. * @return \Symfony\Component\HttpFoundation\RedirectResponse
  167. */
  168. public function batchActionDelete(ProxyQueryInterface $query)
  169. {
  170. if (false === $this->admin->isGranted('DELETE')) {
  171. throw new AccessDeniedException();
  172. }
  173. $modelManager = $this->admin->getModelManager();
  174. try {
  175. $modelManager->batchDelete($this->admin->getClass(), $query);
  176. $this->addFlash('sonata_flash_success', 'flash_batch_delete_success');
  177. } catch ( ModelManagerException $e ) {
  178. $this->addFlash('sonata_flash_error', 'flash_batch_delete_error');
  179. }
  180. return new RedirectResponse($this->admin->generateUrl('list', array('filter' => $this->admin->getFilterParameters())));
  181. }
  182. /**
  183. * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException|\Symfony\Component\Security\Core\Exception\AccessDeniedException
  184. *
  185. * @param mixed $id
  186. *
  187. * @return Response|RedirectResponse
  188. */
  189. public function deleteAction($id)
  190. {
  191. $id = $this->get('request')->get($this->admin->getIdParameter());
  192. $object = $this->admin->getObject($id);
  193. if (!$object) {
  194. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  195. }
  196. if (false === $this->admin->isGranted('DELETE', $object)) {
  197. throw new AccessDeniedException();
  198. }
  199. if ($this->getRestMethod() == 'DELETE') {
  200. // check the csrf token
  201. $this->validateCsrfToken('sonata.delete');
  202. try {
  203. $this->admin->delete($object);
  204. if ($this->isXmlHttpRequest()) {
  205. return $this->renderJson(array('result' => 'ok'));
  206. }
  207. $this->addFlash('sonata_flash_success', 'flash_delete_success');
  208. } catch (ModelManagerException $e) {
  209. if ($this->isXmlHttpRequest()) {
  210. return $this->renderJson(array('result' => 'error'));
  211. }
  212. $this->addFlash('sonata_flash_error', 'flash_delete_error');
  213. }
  214. return new RedirectResponse($this->admin->generateUrl('list'));
  215. }
  216. return $this->render($this->admin->getTemplate('delete'), array(
  217. 'object' => $object,
  218. 'action' => 'delete',
  219. 'csrf_token' => $this->getCsrfToken('sonata.delete')
  220. ));
  221. }
  222. /**
  223. * return the Response object associated to the edit action
  224. *
  225. *
  226. * @param mixed $id
  227. *
  228. * @throws \Symfony\Component\Security\Core\Exception\AccessDeniedException
  229. * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
  230. *
  231. * @return Response
  232. */
  233. public function editAction($id = null)
  234. {
  235. // the key used to lookup the template
  236. $templateKey = 'edit';
  237. $id = $this->get('request')->get($this->admin->getIdParameter());
  238. $object = $this->admin->getObject($id);
  239. if (!$object) {
  240. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  241. }
  242. if (false === $this->admin->isGranted('EDIT', $object)) {
  243. throw new AccessDeniedException();
  244. }
  245. $this->admin->setSubject($object);
  246. /** @var $form \Symfony\Component\Form\Form */
  247. $form = $this->admin->getForm();
  248. $form->setData($object);
  249. if ($this->getRestMethod() == 'POST') {
  250. $form->bind($this->get('request'));
  251. $isFormValid = $form->isValid();
  252. // persist if the form was valid and if in preview mode the preview was approved
  253. if ($isFormValid && (!$this->isInPreviewMode() || $this->isPreviewApproved())) {
  254. $this->admin->update($object);
  255. $this->addFlash('sonata_flash_success', 'flash_edit_success');
  256. if ($this->isXmlHttpRequest()) {
  257. return $this->renderJson(array(
  258. 'result' => 'ok',
  259. 'objectId' => $this->admin->getNormalizedIdentifier($object)
  260. ));
  261. }
  262. // redirect to edit mode
  263. return $this->redirectTo($object);
  264. }
  265. // show an error message if the form failed validation
  266. if (!$isFormValid) {
  267. if (!$this->isXmlHttpRequest()) {
  268. $this->addFlash('sonata_flash_error', 'flash_edit_error');
  269. }
  270. } elseif ($this->isPreviewRequested()) {
  271. // enable the preview template if the form was valid and preview was requested
  272. $templateKey = 'preview';
  273. $this->admin->getShow();
  274. }
  275. }
  276. $view = $form->createView();
  277. // set the theme for the current Admin Form
  278. $this->get('twig')->getExtension('form')->renderer->setTheme($view, $this->admin->getFormTheme());
  279. return $this->render($this->admin->getTemplate($templateKey), array(
  280. 'action' => 'edit',
  281. 'form' => $view,
  282. 'object' => $object,
  283. ));
  284. }
  285. /**
  286. * redirect the user depend on this choice
  287. *
  288. * @param object $object
  289. *
  290. * @return Response
  291. */
  292. public function redirectTo($object)
  293. {
  294. $url = false;
  295. if ($this->get('request')->get('btn_update_and_list')) {
  296. $url = $this->admin->generateUrl('list');
  297. }
  298. if ($this->get('request')->get('btn_create_and_list')) {
  299. $url = $this->admin->generateUrl('list');
  300. }
  301. if ($this->get('request')->get('btn_create_and_create')) {
  302. $params = array();
  303. if ($this->admin->hasActiveSubClass()) {
  304. $params['subclass'] = $this->get('request')->get('subclass');
  305. }
  306. $url = $this->admin->generateUrl('create', $params);
  307. }
  308. if (!$url) {
  309. $url = $this->admin->generateObjectUrl('edit', $object);
  310. }
  311. return new RedirectResponse($url);
  312. }
  313. /**
  314. * return the Response object associated to the batch action
  315. *
  316. * @throws \RuntimeException
  317. * @return Response
  318. */
  319. public function batchAction()
  320. {
  321. if ($this->getRestMethod() != 'POST') {
  322. throw new \RuntimeException('invalid request type, POST expected');
  323. }
  324. $confirmation = $this->get('request')->get('confirmation', false);
  325. if ($data = json_decode($this->get('request')->get('data'), true)) {
  326. $action = $data['action'];
  327. $idx = $data['idx'];
  328. $all_elements = $data['all_elements'];
  329. $this->get('request')->request->replace($data);
  330. } else {
  331. $this->get('request')->request->set('idx', $this->get('request')->get('idx', array()));
  332. $this->get('request')->request->set('all_elements', $this->get('request')->get('all_elements', false));
  333. $action = $this->get('request')->get('action');
  334. $idx = $this->get('request')->get('idx');
  335. $all_elements = $this->get('request')->get('all_elements');
  336. $data = $this->get('request')->request->all();
  337. unset($data['_sonata_csrf_token']);
  338. }
  339. $batchActions = $this->admin->getBatchActions();
  340. if (!array_key_exists($action, $batchActions)) {
  341. throw new \RuntimeException(sprintf('The `%s` batch action is not defined', $action));
  342. }
  343. // check the csrf token
  344. $this->validateCsrfToken('sonata.batch');
  345. $camelizedAction = BaseFieldDescription::camelize($action);
  346. $isRelevantAction = sprintf('batchAction%sIsRelevant', ucfirst($camelizedAction));
  347. if (method_exists($this, $isRelevantAction)) {
  348. $nonRelevantMessage = call_user_func(array($this, $isRelevantAction), $idx, $all_elements);
  349. } else {
  350. $nonRelevantMessage = count($idx) != 0 || $all_elements; // at least one item is selected
  351. }
  352. if (!$nonRelevantMessage) { // default non relevant message (if false of null)
  353. $nonRelevantMessage = 'flash_batch_empty';
  354. }
  355. $datagrid = $this->admin->getDatagrid();
  356. $datagrid->buildPager();
  357. if (true !== $nonRelevantMessage) {
  358. $this->addFlash('sonata_flash_info', $nonRelevantMessage);
  359. return new RedirectResponse($this->admin->generateUrl('list', array('filter' => $this->admin->getFilterParameters())));
  360. }
  361. $askConfirmation = isset($batchActions[$action]['ask_confirmation']) ? $batchActions[$action]['ask_confirmation'] : true;
  362. if ($askConfirmation && $confirmation != 'ok') {
  363. $formView = $datagrid->getForm()->createView();
  364. return $this->render($this->admin->getTemplate('batch_confirmation'), array(
  365. 'action' => 'list',
  366. 'datagrid' => $datagrid,
  367. 'form' => $formView,
  368. 'data' => $data,
  369. 'csrf_token' => $this->getCsrfToken('sonata.batch'),
  370. ));
  371. }
  372. // execute the action, batchActionXxxxx
  373. $final_action = sprintf('batchAction%s', ucfirst($camelizedAction));
  374. if (!method_exists($this, $final_action)) {
  375. throw new \RuntimeException(sprintf('A `%s::%s` method must be created', get_class($this), $final_action));
  376. }
  377. $query = $datagrid->getQuery();
  378. $query->setFirstResult(null);
  379. $query->setMaxResults(null);
  380. if (count($idx) > 0) {
  381. $this->admin->getModelManager()->addIdentifiersToQuery($this->admin->getClass(), $query, $idx);
  382. } elseif (!$all_elements) {
  383. $query = null;
  384. }
  385. return call_user_func(array($this, $final_action), $query);
  386. }
  387. /**
  388. * return the Response object associated to the create action
  389. *
  390. * @throws \Symfony\Component\Security\Core\Exception\AccessDeniedException
  391. * @return Response
  392. */
  393. public function createAction()
  394. {
  395. // the key used to lookup the template
  396. $templateKey = 'edit';
  397. if (false === $this->admin->isGranted('CREATE')) {
  398. throw new AccessDeniedException();
  399. }
  400. $object = $this->admin->getNewInstance();
  401. $this->admin->setSubject($object);
  402. /** @var $form \Symfony\Component\Form\Form */
  403. $form = $this->admin->getForm();
  404. $form->setData($object);
  405. if ($this->getRestMethod()== 'POST') {
  406. $form->bind($this->get('request'));
  407. $isFormValid = $form->isValid();
  408. // persist if the form was valid and if in preview mode the preview was approved
  409. if ($isFormValid && (!$this->isInPreviewMode() || $this->isPreviewApproved())) {
  410. $this->admin->create($object);
  411. if ($this->isXmlHttpRequest()) {
  412. return $this->renderJson(array(
  413. 'result' => 'ok',
  414. 'objectId' => $this->admin->getNormalizedIdentifier($object)
  415. ));
  416. }
  417. $this->addFlash('sonata_flash_success','flash_create_success');
  418. // redirect to edit mode
  419. return $this->redirectTo($object);
  420. }
  421. // show an error message if the form failed validation
  422. if (!$isFormValid) {
  423. if (!$this->isXmlHttpRequest()) {
  424. $this->addFlash('sonata_flash_error', 'flash_create_error');
  425. }
  426. } elseif ($this->isPreviewRequested()) {
  427. // pick the preview template if the form was valid and preview was requested
  428. $templateKey = 'preview';
  429. $this->admin->getShow();
  430. }
  431. }
  432. $view = $form->createView();
  433. // set the theme for the current Admin Form
  434. $this->get('twig')->getExtension('form')->renderer->setTheme($view, $this->admin->getFormTheme());
  435. return $this->render($this->admin->getTemplate($templateKey), array(
  436. 'action' => 'create',
  437. 'form' => $view,
  438. 'object' => $object,
  439. ));
  440. }
  441. /**
  442. * Returns true if the preview is requested to be shown
  443. *
  444. * @return boolean
  445. */
  446. protected function isPreviewRequested()
  447. {
  448. return ($this->get('request')->get('btn_preview') !== null);
  449. }
  450. /**
  451. * Returns true if the preview has been approved
  452. *
  453. * @return boolean
  454. */
  455. protected function isPreviewApproved()
  456. {
  457. return ($this->get('request')->get('btn_preview_approve') !== null);
  458. }
  459. /**
  460. * Returns true if the request is in the preview workflow
  461. *
  462. * That means either a preview is requested or the preview has already been shown
  463. * and it got approved/declined.
  464. *
  465. * @return boolean
  466. */
  467. protected function isInPreviewMode()
  468. {
  469. return $this->admin->supportsPreviewMode()
  470. && ($this->isPreviewRequested()
  471. || $this->isPreviewApproved()
  472. || $this->isPreviewDeclined());
  473. }
  474. /**
  475. * Returns true if the preview has been declined
  476. *
  477. * @return boolean
  478. */
  479. protected function isPreviewDeclined()
  480. {
  481. return ($this->get('request')->get('btn_preview_decline') !== null);
  482. }
  483. /**
  484. * return the Response object associated to the view action
  485. *
  486. * @param null $id
  487. *
  488. * @throws \Symfony\Component\Security\Core\Exception\AccessDeniedException
  489. * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
  490. *
  491. * @return Response
  492. */
  493. public function showAction($id = null)
  494. {
  495. $id = $this->get('request')->get($this->admin->getIdParameter());
  496. $object = $this->admin->getObject($id);
  497. if (!$object) {
  498. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  499. }
  500. if (false === $this->admin->isGranted('VIEW', $object)) {
  501. throw new AccessDeniedException();
  502. }
  503. $this->admin->setSubject($object);
  504. return $this->render($this->admin->getTemplate('show'), array(
  505. 'action' => 'show',
  506. 'object' => $object,
  507. 'elements' => $this->admin->getShow(),
  508. ));
  509. }
  510. /**
  511. * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException|\Symfony\Component\Security\Core\Exception\AccessDeniedException
  512. *
  513. * @param mixed $id
  514. *
  515. * @return Response
  516. */
  517. public function historyAction($id = null)
  518. {
  519. if (false === $this->admin->isGranted('EDIT')) {
  520. throw new AccessDeniedException();
  521. }
  522. $id = $this->get('request')->get($this->admin->getIdParameter());
  523. $object = $this->admin->getObject($id);
  524. if (!$object) {
  525. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  526. }
  527. $manager = $this->get('sonata.admin.audit.manager');
  528. if (!$manager->hasReader($this->admin->getClass())) {
  529. throw new NotFoundHttpException(sprintf('unable to find the audit reader for class : %s', $this->admin->getClass()));
  530. }
  531. $reader = $manager->getReader($this->admin->getClass());
  532. $revisions = $reader->findRevisions($this->admin->getClass(), $id);
  533. return $this->render($this->admin->getTemplate('history'), array(
  534. 'action' => 'history',
  535. 'object' => $object,
  536. 'revisions' => $revisions,
  537. ));
  538. }
  539. /**
  540. * @param null $id
  541. * @param string $revision
  542. *
  543. * @throws \Symfony\Component\Security\Core\Exception\AccessDeniedException
  544. * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
  545. *
  546. * @return Response
  547. */
  548. public function historyViewRevisionAction($id = null, $revision = null)
  549. {
  550. if (false === $this->admin->isGranted('EDIT')) {
  551. throw new AccessDeniedException();
  552. }
  553. $id = $this->get('request')->get($this->admin->getIdParameter());
  554. $object = $this->admin->getObject($id);
  555. if (!$object) {
  556. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  557. }
  558. $manager = $this->get('sonata.admin.audit.manager');
  559. if (!$manager->hasReader($this->admin->getClass())) {
  560. throw new NotFoundHttpException(sprintf('unable to find the audit reader for class : %s', $this->admin->getClass()));
  561. }
  562. $reader = $manager->getReader($this->admin->getClass());
  563. // retrieve the revisioned object
  564. $object = $reader->find($this->admin->getClass(), $id, $revision);
  565. if (!$object) {
  566. throw new NotFoundHttpException(sprintf('unable to find the targeted object `%s` from the revision `%s` with classname : `%s`', $id, $revision, $this->admin->getClass()));
  567. }
  568. $this->admin->setSubject($object);
  569. return $this->render($this->admin->getTemplate('show'), array(
  570. 'action' => 'show',
  571. 'object' => $object,
  572. 'elements' => $this->admin->getShow(),
  573. ));
  574. }
  575. /**
  576. * @param Request $request
  577. *
  578. * @throws \RuntimeException
  579. * @throws \Symfony\Component\Security\Core\Exception\AccessDeniedException
  580. *
  581. * @return Response
  582. */
  583. public function exportAction(Request $request)
  584. {
  585. if (false === $this->admin->isGranted('EXPORT')) {
  586. throw new AccessDeniedException();
  587. }
  588. $format = $request->get('format');
  589. $allowedExportFormats = (array) $this->admin->getExportFormats();
  590. if (!in_array($format, $allowedExportFormats) ) {
  591. throw new \RuntimeException(sprintf('Export in format `%s` is not allowed for class: `%s`. Allowed formats are: `%s`', $format, $this->admin->getClass(), implode(', ', $allowedExportFormats)));
  592. }
  593. $filename = sprintf('export_%s_%s.%s',
  594. strtolower(substr($this->admin->getClass(), strripos($this->admin->getClass(), '\\') + 1)),
  595. date('Y_m_d_H_i_s', strtotime('now')),
  596. $format
  597. );
  598. return $this->get('sonata.admin.exporter')->getResponse($format, $filename, $this->admin->getDataSourceIterator());
  599. }
  600. /**
  601. * Gets ACL users
  602. *
  603. * @return \Traversable
  604. */
  605. protected function getAclUsers()
  606. {
  607. $aclUsers = array();
  608. $userManagerServiceName = $this->container->getParameter('sonata.admin.security.acl_user_manager');
  609. if ($userManagerServiceName !== null && $this->has($userManagerServiceName)) {
  610. $userManager = $this->get($userManagerServiceName);
  611. if (method_exists($userManager, 'findUsers')) {
  612. $aclUsers = $userManager->findUsers();
  613. }
  614. }
  615. return is_array($aclUsers) ? new \ArrayIterator($aclUsers) : $aclUsers;
  616. }
  617. /**
  618. * return the Response object associated to the acl action
  619. *
  620. * @param null $id
  621. *
  622. * @throws \Symfony\Component\Security\Core\Exception\AccessDeniedException
  623. * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
  624. *
  625. * @return Response
  626. */
  627. public function aclAction($id = null)
  628. {
  629. if (!$this->admin->isAclEnabled()) {
  630. throw new NotFoundHttpException('ACL are not enabled for this admin');
  631. }
  632. $id = $this->get('request')->get($this->admin->getIdParameter());
  633. $object = $this->admin->getObject($id);
  634. if (!$object) {
  635. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  636. }
  637. if (false === $this->admin->isGranted('MASTER', $object)) {
  638. throw new AccessDeniedException();
  639. }
  640. $this->admin->setSubject($object);
  641. $aclUsers = $this->getAclUsers();
  642. $adminObjectAclManipulator = $this->get('sonata.admin.object.manipulator.acl.admin');
  643. $adminObjectAclData = new AdminObjectAclData(
  644. $this->admin,
  645. $object,
  646. $aclUsers,
  647. $adminObjectAclManipulator->getMaskBuilderClass()
  648. );
  649. $form = $adminObjectAclManipulator->createForm($adminObjectAclData);
  650. $request = $this->getRequest();
  651. if ($request->getMethod() === 'POST') {
  652. $form->bind($request);
  653. if ($form->isValid()) {
  654. $adminObjectAclManipulator->updateAcl($adminObjectAclData);
  655. $this->addFlash('sonata_flash_success', 'flash_acl_edit_success');
  656. return new RedirectResponse($this->admin->generateObjectUrl('acl', $object));
  657. }
  658. }
  659. return $this->render($this->admin->getTemplate('acl'), array(
  660. 'action' => 'acl',
  661. 'permissions' => $adminObjectAclData->getUserPermissions(),
  662. 'object' => $object,
  663. 'users' => $aclUsers,
  664. 'form' => $form->createView()
  665. ));
  666. }
  667. /**
  668. * Adds a flash message for type.
  669. *
  670. * @param string $type
  671. * @param string $message
  672. */
  673. public function addFlash($type, $message)
  674. {
  675. $this->get('session')
  676. ->getFlashBag()
  677. ->add($type, $message);
  678. }
  679. /**
  680. * Validate CSRF token for action with out form
  681. *
  682. * @param string $intention
  683. *
  684. * @throws \RuntimeException
  685. */
  686. public function validateCsrfToken($intention)
  687. {
  688. if (!$this->container->has('form.csrf_provider')) {
  689. return;
  690. }
  691. if (!$this->container->get('form.csrf_provider')->isCsrfTokenValid($intention, $this->get('request')->request->get('_sonata_csrf_toke', false))) {
  692. throw new HttpException(400, "The csrf token is not valid, CSRF attack ?");
  693. }
  694. }
  695. /**
  696. * @param $intention
  697. *
  698. * @return string
  699. */
  700. public function getCsrfToken($intention)
  701. {
  702. if (!$this->container->has('form.csrf_provider')) {
  703. return false;
  704. }
  705. return $this->container->get('form.csrf_provider')->generateCsrfToken($intention);
  706. }
  707. }