CRUDController.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878
  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. protected 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. protected 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. protected 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. protected 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(
  208. 'sonata_flash_success',
  209. $this->admin->trans('flash_delete_success', array('%name%' => $this->admin->toString($object)),
  210. 'SonataAdminBundle')
  211. );
  212. } catch (ModelManagerException $e) {
  213. if ($this->isXmlHttpRequest()) {
  214. return $this->renderJson(array('result' => 'error'));
  215. }
  216. $this->addFlash(
  217. 'sonata_flash_error',
  218. $this->admin->trans('flash_delete_error', array('%name%' => $this->admin->toString($object)),
  219. 'SonataAdminBundle')
  220. );
  221. }
  222. return new RedirectResponse($this->admin->generateUrl('list'));
  223. }
  224. return $this->render($this->admin->getTemplate('delete'), array(
  225. 'object' => $object,
  226. 'action' => 'delete',
  227. 'csrf_token' => $this->getCsrfToken('sonata.delete')
  228. ));
  229. }
  230. /**
  231. * return the Response object associated to the edit action
  232. *
  233. *
  234. * @param mixed $id
  235. *
  236. * @throws \Symfony\Component\Security\Core\Exception\AccessDeniedException
  237. * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
  238. *
  239. * @return Response
  240. */
  241. public function editAction($id = null)
  242. {
  243. // the key used to lookup the template
  244. $templateKey = 'edit';
  245. $id = $this->get('request')->get($this->admin->getIdParameter());
  246. $object = $this->admin->getObject($id);
  247. if (!$object) {
  248. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  249. }
  250. if (false === $this->admin->isGranted('EDIT', $object)) {
  251. throw new AccessDeniedException();
  252. }
  253. $this->admin->setSubject($object);
  254. /** @var $form \Symfony\Component\Form\Form */
  255. $form = $this->admin->getForm();
  256. $form->setData($object);
  257. if ($this->getRestMethod() == 'POST') {
  258. $form->submit($this->get('request'));
  259. $isFormValid = $form->isValid();
  260. // persist if the form was valid and if in preview mode the preview was approved
  261. if ($isFormValid && (!$this->isInPreviewMode() || $this->isPreviewApproved())) {
  262. $this->admin->update($object);
  263. if ($this->isXmlHttpRequest()) {
  264. return $this->renderJson(array(
  265. 'result' => 'ok',
  266. 'objectId' => $this->admin->getNormalizedIdentifier($object)
  267. ));
  268. }
  269. $this->addFlash('sonata_flash_success', $this->admin->trans('flash_edit_success', array('%name%' => $this->admin->toString($object)), 'SonataAdminBundle'));
  270. // redirect to edit mode
  271. return $this->redirectTo($object);
  272. }
  273. // show an error message if the form failed validation
  274. if (!$isFormValid) {
  275. if (!$this->isXmlHttpRequest()) {
  276. $this->addFlash('sonata_flash_error', $this->admin->trans('flash_edit_error', array('%name%' => $this->admin->toString($object)), 'SonataAdminBundle'));
  277. }
  278. } elseif ($this->isPreviewRequested()) {
  279. // enable the preview template if the form was valid and preview was requested
  280. $templateKey = 'preview';
  281. $this->admin->getShow();
  282. }
  283. }
  284. $view = $form->createView();
  285. // set the theme for the current Admin Form
  286. $this->get('twig')->getExtension('form')->renderer->setTheme($view, $this->admin->getFormTheme());
  287. return $this->render($this->admin->getTemplate($templateKey), array(
  288. 'action' => 'edit',
  289. 'form' => $view,
  290. 'object' => $object,
  291. ));
  292. }
  293. /**
  294. * redirect the user depend on this choice
  295. *
  296. * @param object $object
  297. *
  298. * @return Response
  299. */
  300. protected function redirectTo($object)
  301. {
  302. $url = false;
  303. if ($this->get('request')->get('btn_update_and_list')) {
  304. $url = $this->admin->generateUrl('list');
  305. }
  306. if ($this->get('request')->get('btn_create_and_list')) {
  307. $url = $this->admin->generateUrl('list');
  308. }
  309. if ($this->get('request')->get('btn_create_and_create')) {
  310. $params = array();
  311. if ($this->admin->hasActiveSubClass()) {
  312. $params['subclass'] = $this->get('request')->get('subclass');
  313. }
  314. $url = $this->admin->generateUrl('create', $params);
  315. }
  316. if (!$url) {
  317. $url = $this->admin->generateObjectUrl('edit', $object);
  318. }
  319. return new RedirectResponse($url);
  320. }
  321. /**
  322. * return the Response object associated to the batch action
  323. *
  324. * @throws \RuntimeException
  325. * @return Response
  326. */
  327. public function batchAction()
  328. {
  329. $restMethod = $this->getRestMethod();
  330. if ('POST' !== $restMethod) {
  331. throw $this->createNotFoundException(sprintf('Invalid request type "%s", POST expected', $restMethod));
  332. }
  333. // check the csrf token
  334. $this->validateCsrfToken('sonata.batch');
  335. $confirmation = $this->get('request')->get('confirmation', false);
  336. if ($data = json_decode($this->get('request')->get('data'), true)) {
  337. $action = $data['action'];
  338. $idx = $data['idx'];
  339. $allElements = $data['all_elements'];
  340. $this->get('request')->request->replace($data);
  341. } else {
  342. $this->get('request')->request->set('idx', $this->get('request')->get('idx', array()));
  343. $this->get('request')->request->set('all_elements', $this->get('request')->get('all_elements', false));
  344. $action = $this->get('request')->get('action');
  345. $idx = $this->get('request')->get('idx');
  346. $allElements = $this->get('request')->get('all_elements');
  347. $data = $this->get('request')->request->all();
  348. unset($data['_sonata_csrf_token']);
  349. }
  350. $batchActions = $this->admin->getBatchActions();
  351. if (!array_key_exists($action, $batchActions)) {
  352. throw new \RuntimeException(sprintf('The `%s` batch action is not defined', $action));
  353. }
  354. $camelizedAction = BaseFieldDescription::camelize($action);
  355. $isRelevantAction = sprintf('batchAction%sIsRelevant', ucfirst($camelizedAction));
  356. if (method_exists($this, $isRelevantAction)) {
  357. $nonRelevantMessage = call_user_func(array($this, $isRelevantAction), $idx, $allElements);
  358. } else {
  359. $nonRelevantMessage = count($idx) != 0 || $allElements; // at least one item is selected
  360. }
  361. if (!$nonRelevantMessage) { // default non relevant message (if false of null)
  362. $nonRelevantMessage = 'flash_batch_empty';
  363. }
  364. $datagrid = $this->admin->getDatagrid();
  365. $datagrid->buildPager();
  366. if (true !== $nonRelevantMessage) {
  367. $this->addFlash('sonata_flash_info', $nonRelevantMessage);
  368. return new RedirectResponse($this->admin->generateUrl('list', array('filter' => $this->admin->getFilterParameters())));
  369. }
  370. $askConfirmation = isset($batchActions[$action]['ask_confirmation']) ? $batchActions[$action]['ask_confirmation'] : true;
  371. if ($askConfirmation && $confirmation != 'ok') {
  372. $actionLabel = $this->admin->trans($this->admin->getTranslationLabel($action, 'action'));
  373. $formView = $datagrid->getForm()->createView();
  374. return $this->render($this->admin->getTemplate('batch_confirmation'), array(
  375. 'action' => 'list',
  376. 'action_label' => $actionLabel,
  377. 'datagrid' => $datagrid,
  378. 'form' => $formView,
  379. 'data' => $data,
  380. 'csrf_token' => $this->getCsrfToken('sonata.batch'),
  381. ));
  382. }
  383. // execute the action, batchActionXxxxx
  384. $finalAction = sprintf('batchAction%s', ucfirst($camelizedAction));
  385. if (!method_exists($this, $finalAction)) {
  386. throw new \RuntimeException(sprintf('A `%s::%s` method must be created', get_class($this), $finalAction));
  387. }
  388. $query = $datagrid->getQuery();
  389. $query->setFirstResult(null);
  390. $query->setMaxResults(null);
  391. if (count($idx) > 0) {
  392. $this->admin->getModelManager()->addIdentifiersToQuery($this->admin->getClass(), $query, $idx);
  393. } elseif (!$allElements) {
  394. $query = null;
  395. }
  396. return call_user_func(array($this, $finalAction), $query);
  397. }
  398. /**
  399. * return the Response object associated to the create action
  400. *
  401. * @throws \Symfony\Component\Security\Core\Exception\AccessDeniedException
  402. * @return Response
  403. */
  404. public function createAction()
  405. {
  406. // the key used to lookup the template
  407. $templateKey = 'edit';
  408. if (false === $this->admin->isGranted('CREATE')) {
  409. throw new AccessDeniedException();
  410. }
  411. $object = $this->admin->getNewInstance();
  412. $this->admin->setSubject($object);
  413. /** @var $form \Symfony\Component\Form\Form */
  414. $form = $this->admin->getForm();
  415. $form->setData($object);
  416. if ($this->getRestMethod()== 'POST') {
  417. $form->submit($this->get('request'));
  418. $isFormValid = $form->isValid();
  419. // persist if the form was valid and if in preview mode the preview was approved
  420. if ($isFormValid && (!$this->isInPreviewMode() || $this->isPreviewApproved())) {
  421. $this->admin->create($object);
  422. if ($this->isXmlHttpRequest()) {
  423. return $this->renderJson(array(
  424. 'result' => 'ok',
  425. 'objectId' => $this->admin->getNormalizedIdentifier($object)
  426. ));
  427. }
  428. $this->addFlash('sonata_flash_success', $this->admin->trans('flash_create_success', array('%name%' => $this->admin->toString($object)), 'SonataAdminBundle'));
  429. // redirect to edit mode
  430. return $this->redirectTo($object);
  431. }
  432. // show an error message if the form failed validation
  433. if (!$isFormValid) {
  434. if (!$this->isXmlHttpRequest()) {
  435. $this->addFlash('sonata_flash_error', $this->admin->trans('flash_create_error', array('%name%' => $this->admin->toString($object)), 'SonataAdminBundle'));
  436. }
  437. } elseif ($this->isPreviewRequested()) {
  438. // pick the preview template if the form was valid and preview was requested
  439. $templateKey = 'preview';
  440. $this->admin->getShow();
  441. }
  442. }
  443. $view = $form->createView();
  444. // set the theme for the current Admin Form
  445. $this->get('twig')->getExtension('form')->renderer->setTheme($view, $this->admin->getFormTheme());
  446. return $this->render($this->admin->getTemplate($templateKey), array(
  447. 'action' => 'create',
  448. 'form' => $view,
  449. 'object' => $object,
  450. ));
  451. }
  452. /**
  453. * Returns true if the preview is requested to be shown
  454. *
  455. * @return boolean
  456. */
  457. protected function isPreviewRequested()
  458. {
  459. return ($this->get('request')->get('btn_preview') !== null);
  460. }
  461. /**
  462. * Returns true if the preview has been approved
  463. *
  464. * @return boolean
  465. */
  466. protected function isPreviewApproved()
  467. {
  468. return ($this->get('request')->get('btn_preview_approve') !== null);
  469. }
  470. /**
  471. * Returns true if the request is in the preview workflow
  472. *
  473. * That means either a preview is requested or the preview has already been shown
  474. * and it got approved/declined.
  475. *
  476. * @return boolean
  477. */
  478. protected function isInPreviewMode()
  479. {
  480. return $this->admin->supportsPreviewMode()
  481. && ($this->isPreviewRequested()
  482. || $this->isPreviewApproved()
  483. || $this->isPreviewDeclined());
  484. }
  485. /**
  486. * Returns true if the preview has been declined
  487. *
  488. * @return boolean
  489. */
  490. protected function isPreviewDeclined()
  491. {
  492. return ($this->get('request')->get('btn_preview_decline') !== null);
  493. }
  494. /**
  495. * return the Response object associated to the view action
  496. *
  497. * @param null $id
  498. *
  499. * @throws \Symfony\Component\Security\Core\Exception\AccessDeniedException
  500. * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
  501. *
  502. * @return Response
  503. */
  504. public function showAction($id = null)
  505. {
  506. $id = $this->get('request')->get($this->admin->getIdParameter());
  507. $object = $this->admin->getObject($id);
  508. if (!$object) {
  509. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  510. }
  511. if (false === $this->admin->isGranted('VIEW', $object)) {
  512. throw new AccessDeniedException();
  513. }
  514. $this->admin->setSubject($object);
  515. return $this->render($this->admin->getTemplate('show'), array(
  516. 'action' => 'show',
  517. 'object' => $object,
  518. 'elements' => $this->admin->getShow(),
  519. ));
  520. }
  521. /**
  522. * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException|\Symfony\Component\Security\Core\Exception\AccessDeniedException
  523. *
  524. * @param mixed $id
  525. *
  526. * @return Response
  527. */
  528. public function historyAction($id = null)
  529. {
  530. if (false === $this->admin->isGranted('EDIT')) {
  531. throw new AccessDeniedException();
  532. }
  533. $id = $this->get('request')->get($this->admin->getIdParameter());
  534. $object = $this->admin->getObject($id);
  535. if (!$object) {
  536. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  537. }
  538. $manager = $this->get('sonata.admin.audit.manager');
  539. if (!$manager->hasReader($this->admin->getClass())) {
  540. throw new NotFoundHttpException(sprintf('unable to find the audit reader for class : %s', $this->admin->getClass()));
  541. }
  542. $reader = $manager->getReader($this->admin->getClass());
  543. $revisions = $reader->findRevisions($this->admin->getClass(), $id);
  544. return $this->render($this->admin->getTemplate('history'), array(
  545. 'action' => 'history',
  546. 'object' => $object,
  547. 'revisions' => $revisions,
  548. ));
  549. }
  550. /**
  551. * @param null $id
  552. * @param string $revision
  553. *
  554. * @throws \Symfony\Component\Security\Core\Exception\AccessDeniedException
  555. * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
  556. *
  557. * @return Response
  558. */
  559. public function historyViewRevisionAction($id = null, $revision = null)
  560. {
  561. if (false === $this->admin->isGranted('EDIT')) {
  562. throw new AccessDeniedException();
  563. }
  564. $id = $this->get('request')->get($this->admin->getIdParameter());
  565. $object = $this->admin->getObject($id);
  566. if (!$object) {
  567. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  568. }
  569. $manager = $this->get('sonata.admin.audit.manager');
  570. if (!$manager->hasReader($this->admin->getClass())) {
  571. throw new NotFoundHttpException(sprintf('unable to find the audit reader for class : %s', $this->admin->getClass()));
  572. }
  573. $reader = $manager->getReader($this->admin->getClass());
  574. // retrieve the revisioned object
  575. $object = $reader->find($this->admin->getClass(), $id, $revision);
  576. if (!$object) {
  577. throw new NotFoundHttpException(sprintf('unable to find the targeted object `%s` from the revision `%s` with classname : `%s`', $id, $revision, $this->admin->getClass()));
  578. }
  579. $this->admin->setSubject($object);
  580. return $this->render($this->admin->getTemplate('show'), array(
  581. 'action' => 'show',
  582. 'object' => $object,
  583. 'elements' => $this->admin->getShow(),
  584. ));
  585. }
  586. /**
  587. * @param Request $request
  588. *
  589. * @throws \RuntimeException
  590. * @throws \Symfony\Component\Security\Core\Exception\AccessDeniedException
  591. *
  592. * @return Response
  593. */
  594. public function exportAction(Request $request)
  595. {
  596. if (false === $this->admin->isGranted('EXPORT')) {
  597. throw new AccessDeniedException();
  598. }
  599. $format = $request->get('format');
  600. $allowedExportFormats = (array) $this->admin->getExportFormats();
  601. if (!in_array($format, $allowedExportFormats) ) {
  602. throw new \RuntimeException(sprintf('Export in format `%s` is not allowed for class: `%s`. Allowed formats are: `%s`', $format, $this->admin->getClass(), implode(', ', $allowedExportFormats)));
  603. }
  604. $filename = sprintf('export_%s_%s.%s',
  605. strtolower(substr($this->admin->getClass(), strripos($this->admin->getClass(), '\\') + 1)),
  606. date('Y_m_d_H_i_s', strtotime('now')),
  607. $format
  608. );
  609. return $this->get('sonata.admin.exporter')->getResponse($format, $filename, $this->admin->getDataSourceIterator());
  610. }
  611. /**
  612. * Gets ACL users
  613. *
  614. * @return \Traversable
  615. */
  616. protected function getAclUsers()
  617. {
  618. $aclUsers = array();
  619. $userManagerServiceName = $this->container->getParameter('sonata.admin.security.acl_user_manager');
  620. if ($userManagerServiceName !== null && $this->has($userManagerServiceName)) {
  621. $userManager = $this->get($userManagerServiceName);
  622. if (method_exists($userManager, 'findUsers')) {
  623. $aclUsers = $userManager->findUsers();
  624. }
  625. }
  626. return is_array($aclUsers) ? new \ArrayIterator($aclUsers) : $aclUsers;
  627. }
  628. /**
  629. * return the Response object associated to the acl action
  630. *
  631. * @param null $id
  632. *
  633. * @throws \Symfony\Component\Security\Core\Exception\AccessDeniedException
  634. * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
  635. *
  636. * @return Response
  637. */
  638. public function aclAction($id = null)
  639. {
  640. if (!$this->admin->isAclEnabled()) {
  641. throw new NotFoundHttpException('ACL are not enabled for this admin');
  642. }
  643. $id = $this->get('request')->get($this->admin->getIdParameter());
  644. $object = $this->admin->getObject($id);
  645. if (!$object) {
  646. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  647. }
  648. if (false === $this->admin->isGranted('MASTER', $object)) {
  649. throw new AccessDeniedException();
  650. }
  651. $this->admin->setSubject($object);
  652. $aclUsers = $this->getAclUsers();
  653. $adminObjectAclManipulator = $this->get('sonata.admin.object.manipulator.acl.admin');
  654. $adminObjectAclData = new AdminObjectAclData(
  655. $this->admin,
  656. $object,
  657. $aclUsers,
  658. $adminObjectAclManipulator->getMaskBuilderClass()
  659. );
  660. $form = $adminObjectAclManipulator->createForm($adminObjectAclData);
  661. $request = $this->getRequest();
  662. if ($request->getMethod() === 'POST') {
  663. $form->submit($request);
  664. if ($form->isValid()) {
  665. $adminObjectAclManipulator->updateAcl($adminObjectAclData);
  666. $this->addFlash('sonata_flash_success', 'flash_acl_edit_success');
  667. return new RedirectResponse($this->admin->generateObjectUrl('acl', $object));
  668. }
  669. }
  670. return $this->render($this->admin->getTemplate('acl'), array(
  671. 'action' => 'acl',
  672. 'permissions' => $adminObjectAclData->getUserPermissions(),
  673. 'object' => $object,
  674. 'users' => $aclUsers,
  675. 'form' => $form->createView()
  676. ));
  677. }
  678. /**
  679. * Adds a flash message for type.
  680. *
  681. * @param string $type
  682. * @param string $message
  683. */
  684. protected function addFlash($type, $message)
  685. {
  686. $this->get('session')
  687. ->getFlashBag()
  688. ->add($type, $message);
  689. }
  690. /**
  691. * Validate CSRF token for action with out form
  692. *
  693. * @param string $intention
  694. *
  695. * @throws \RuntimeException
  696. */
  697. protected function validateCsrfToken($intention)
  698. {
  699. if (!$this->container->has('form.csrf_provider')) {
  700. return;
  701. }
  702. if (!$this->container->get('form.csrf_provider')->isCsrfTokenValid($intention, $this->get('request')->request->get('_sonata_csrf_token', false))) {
  703. throw new HttpException(400, "The csrf token is not valid, CSRF attack ?");
  704. }
  705. }
  706. /**
  707. * @param $intention
  708. *
  709. * @return string
  710. */
  711. protected function getCsrfToken($intention)
  712. {
  713. if (!$this->container->has('form.csrf_provider')) {
  714. return false;
  715. }
  716. return $this->container->get('form.csrf_provider')->generateCsrfToken($intention);
  717. }
  718. }