CRUDController.php 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108
  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. use Sonata\AdminBundle\Admin\AdminInterface;
  24. use Psr\Log\NullLogger;
  25. class CRUDController extends Controller
  26. {
  27. /**
  28. * The related Admin class
  29. *
  30. * @var AdminInterface
  31. */
  32. protected $admin;
  33. /**
  34. * Render JSON
  35. *
  36. * @param mixed $data
  37. * @param integer $status
  38. * @param array $headers
  39. *
  40. * @return Response with json encoded data
  41. */
  42. protected function renderJson($data, $status = 200, $headers = array())
  43. {
  44. // fake content-type so browser does not show the download popup when this
  45. // response is rendered through an iframe (used by the jquery.form.js plugin)
  46. // => don't know yet if it is the best solution
  47. if ($this->get('request')->get('_xml_http_request')
  48. && strpos($this->get('request')->headers->get('Content-Type'), 'multipart/form-data') === 0) {
  49. $headers['Content-Type'] = 'text/plain';
  50. } else {
  51. $headers['Content-Type'] = 'application/json';
  52. }
  53. return new Response(json_encode($data), $status, $headers);
  54. }
  55. /**
  56. * Returns true if the request is a XMLHttpRequest.
  57. *
  58. * @return bool True if the request is an XMLHttpRequest, false otherwise
  59. */
  60. protected function isXmlHttpRequest()
  61. {
  62. return $this->get('request')->isXmlHttpRequest() || $this->get('request')->get('_xml_http_request');
  63. }
  64. /**
  65. * Returns the correct RESTful verb, given either by the request itself or
  66. * via the "_method" parameter.
  67. *
  68. * @return string HTTP method, either
  69. */
  70. protected function getRestMethod()
  71. {
  72. $request = $this->getRequest();
  73. if (Request::getHttpMethodParameterOverride() || !$request->request->has('_method')) {
  74. return $request->getMethod();
  75. }
  76. return $request->request->get('_method');
  77. }
  78. /**
  79. * Sets the Container associated with this Controller.
  80. *
  81. * @param ContainerInterface $container A ContainerInterface instance
  82. */
  83. public function setContainer(ContainerInterface $container = null)
  84. {
  85. $this->container = $container;
  86. $this->configure();
  87. }
  88. /**
  89. * Contextualize the admin class depends on the current request
  90. *
  91. * @throws \RuntimeException
  92. */
  93. protected function configure()
  94. {
  95. $adminCode = $this->container->get('request')->get('_sonata_admin');
  96. if (!$adminCode) {
  97. throw new \RuntimeException(sprintf(
  98. 'There is no `_sonata_admin` defined for the controller `%s` and the current route `%s`',
  99. get_class($this),
  100. $this->container->get('request')->get('_route')
  101. ));
  102. }
  103. $this->admin = $this->container->get('sonata.admin.pool')->getAdminByAdminCode($adminCode);
  104. if (!$this->admin) {
  105. throw new \RuntimeException(sprintf(
  106. 'Unable to find the admin class related to the current controller (%s)',
  107. get_class($this)
  108. ));
  109. }
  110. $rootAdmin = $this->admin;
  111. if ($this->admin->isChild()) {
  112. $this->admin->setCurrentChild(true);
  113. $rootAdmin = $rootAdmin->getParent();
  114. }
  115. $request = $this->container->get('request');
  116. $rootAdmin->setRequest($request);
  117. if ($request->get('uniqid')) {
  118. $this->admin->setUniqid($request->get('uniqid'));
  119. }
  120. }
  121. /**
  122. * Proxy for the logger service of the container.
  123. * If no such service is found, a NullLogger is returned.
  124. *
  125. * @return Psr\Log\LoggerInterface
  126. */
  127. protected function getLogger()
  128. {
  129. if ($this->container->has('logger')) {
  130. return $this->container->get('logger');
  131. } else {
  132. return new NullLogger();
  133. }
  134. }
  135. /**
  136. * Returns the base template name
  137. *
  138. * @return string The template name
  139. */
  140. protected function getBaseTemplate()
  141. {
  142. if ($this->isXmlHttpRequest()) {
  143. return $this->admin->getTemplate('ajax');
  144. }
  145. return $this->admin->getTemplate('layout');
  146. }
  147. /**
  148. * {@inheritdoc}
  149. */
  150. public function render($view, array $parameters = array(), Response $response = null)
  151. {
  152. $parameters['admin'] = isset($parameters['admin']) ?
  153. $parameters['admin'] :
  154. $this->admin;
  155. $parameters['base_template'] = isset($parameters['base_template']) ?
  156. $parameters['base_template'] :
  157. $this->getBaseTemplate();
  158. $parameters['admin_pool'] = $this->get('sonata.admin.pool');
  159. return parent::render($view, $parameters, $response);
  160. }
  161. private function logModelManagerException($e)
  162. {
  163. $context = array('exception' => $e);
  164. if ($e->getPrevious()) {
  165. $context['previous_exception_message'] = $e->getPrevious()->getMessage();
  166. }
  167. $this->getLogger()->error($e->getMessage(), $context);
  168. }
  169. /**
  170. * List action
  171. *
  172. * @return Response
  173. *
  174. * @throws AccessDeniedException If access is not granted
  175. */
  176. public function listAction()
  177. {
  178. if (false === $this->admin->isGranted('LIST')) {
  179. throw new AccessDeniedException();
  180. }
  181. $datagrid = $this->admin->getDatagrid();
  182. $formView = $datagrid->getForm()->createView();
  183. // set the theme for the current Admin Form
  184. $this->get('twig')->getExtension('form')->renderer->setTheme($formView, $this->admin->getFilterTheme());
  185. return $this->render($this->admin->getTemplate('list'), array(
  186. 'action' => 'list',
  187. 'form' => $formView,
  188. 'datagrid' => $datagrid,
  189. 'csrf_token' => $this->getCsrfToken('sonata.batch'),
  190. ));
  191. }
  192. /**
  193. * Execute a batch delete
  194. *
  195. * @param ProxyQueryInterface $query
  196. *
  197. * @return RedirectResponse
  198. *
  199. * @throws AccessDeniedException If access is not granted
  200. */
  201. public function batchActionDelete(ProxyQueryInterface $query)
  202. {
  203. if (false === $this->admin->isGranted('DELETE')) {
  204. throw new AccessDeniedException();
  205. }
  206. $modelManager = $this->admin->getModelManager();
  207. try {
  208. $modelManager->batchDelete($this->admin->getClass(), $query);
  209. $this->addFlash('sonata_flash_success', 'flash_batch_delete_success');
  210. } catch (ModelManagerException $e) {
  211. $this->logModelManagerException($e);
  212. $this->addFlash('sonata_flash_error', 'flash_batch_delete_error');
  213. }
  214. return new RedirectResponse($this->admin->generateUrl(
  215. 'list',
  216. array('filter' => $this->admin->getFilterParameters())
  217. ));
  218. }
  219. /**
  220. * Delete action
  221. *
  222. * @param int|string|null $id
  223. *
  224. * @return Response|RedirectResponse
  225. *
  226. * @throws NotFoundHttpException If the object does not exist
  227. * @throws AccessDeniedException If access is not granted
  228. */
  229. public function deleteAction($id)
  230. {
  231. $id = $this->get('request')->get($this->admin->getIdParameter());
  232. $object = $this->admin->getObject($id);
  233. if (!$object) {
  234. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  235. }
  236. if (false === $this->admin->isGranted('DELETE', $object)) {
  237. throw new AccessDeniedException();
  238. }
  239. if ($this->getRestMethod() == 'DELETE') {
  240. // check the csrf token
  241. $this->validateCsrfToken('sonata.delete');
  242. try {
  243. $this->admin->delete($object);
  244. if ($this->isXmlHttpRequest()) {
  245. return $this->renderJson(array('result' => 'ok'));
  246. }
  247. $this->addFlash(
  248. 'sonata_flash_success',
  249. $this->admin->trans(
  250. 'flash_delete_success',
  251. array('%name%' => $this->admin->toString($object)),
  252. 'SonataAdminBundle'
  253. )
  254. );
  255. } catch (ModelManagerException $e) {
  256. $this->logModelManagerException($e);
  257. if ($this->isXmlHttpRequest()) {
  258. return $this->renderJson(array('result' => 'error'));
  259. }
  260. $this->addFlash(
  261. 'sonata_flash_error',
  262. $this->admin->trans(
  263. 'flash_delete_error',
  264. array('%name%' => $this->admin->toString($object)),
  265. 'SonataAdminBundle'
  266. )
  267. );
  268. }
  269. return $this->redirectTo($object);
  270. }
  271. return $this->render($this->admin->getTemplate('delete'), array(
  272. 'object' => $object,
  273. 'action' => 'delete',
  274. 'csrf_token' => $this->getCsrfToken('sonata.delete')
  275. ));
  276. }
  277. /**
  278. * Edit action
  279. *
  280. * @param int|string|null $id
  281. *
  282. * @return Response|RedirectResponse
  283. *
  284. * @throws NotFoundHttpException If the object does not exist
  285. * @throws AccessDeniedException If access is not granted
  286. */
  287. public function editAction($id = null)
  288. {
  289. // the key used to lookup the template
  290. $templateKey = 'edit';
  291. $id = $this->get('request')->get($this->admin->getIdParameter());
  292. $object = $this->admin->getObject($id);
  293. if (!$object) {
  294. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  295. }
  296. if (false === $this->admin->isGranted('EDIT', $object)) {
  297. throw new AccessDeniedException();
  298. }
  299. $this->admin->setSubject($object);
  300. /** @var $form \Symfony\Component\Form\Form */
  301. $form = $this->admin->getForm();
  302. $form->setData($object);
  303. if ($this->getRestMethod() == 'POST') {
  304. $form->submit($this->get('request'));
  305. $isFormValid = $form->isValid();
  306. // persist if the form was valid and if in preview mode the preview was approved
  307. if ($isFormValid && (!$this->isInPreviewMode() || $this->isPreviewApproved())) {
  308. try {
  309. $object = $this->admin->update($object);
  310. if ($this->isXmlHttpRequest()) {
  311. return $this->renderJson(array(
  312. 'result' => 'ok',
  313. 'objectId' => $this->admin->getNormalizedIdentifier($object)
  314. ));
  315. }
  316. $this->addFlash(
  317. 'sonata_flash_success',
  318. $this->admin->trans(
  319. 'flash_edit_success',
  320. array('%name%' => $this->admin->toString($object)),
  321. 'SonataAdminBundle'
  322. )
  323. );
  324. // redirect to edit mode
  325. return $this->redirectTo($object);
  326. } catch (ModelManagerException $e) {
  327. $this->logModelManagerException($e);
  328. $isFormValid = false;
  329. }
  330. }
  331. // show an error message if the form failed validation
  332. if (!$isFormValid) {
  333. if (!$this->isXmlHttpRequest()) {
  334. $this->addFlash(
  335. 'sonata_flash_error',
  336. $this->admin->trans(
  337. 'flash_edit_error',
  338. array('%name%' => $this->admin->toString($object)),
  339. 'SonataAdminBundle'
  340. )
  341. );
  342. }
  343. } elseif ($this->isPreviewRequested()) {
  344. // enable the preview template if the form was valid and preview was requested
  345. $templateKey = 'preview';
  346. $this->admin->getShow();
  347. }
  348. }
  349. $view = $form->createView();
  350. // set the theme for the current Admin Form
  351. $this->get('twig')->getExtension('form')->renderer->setTheme($view, $this->admin->getFormTheme());
  352. return $this->render($this->admin->getTemplate($templateKey), array(
  353. 'action' => 'edit',
  354. 'form' => $view,
  355. 'object' => $object,
  356. ));
  357. }
  358. /**
  359. * Redirect the user depend on this choice
  360. *
  361. * @param object $object
  362. *
  363. * @return RedirectResponse
  364. */
  365. protected function redirectTo($object)
  366. {
  367. $url = false;
  368. if (null !== $this->get('request')->get('btn_update_and_list')) {
  369. $url = $this->admin->generateUrl('list');
  370. }
  371. if (null !== $this->get('request')->get('btn_create_and_list')) {
  372. $url = $this->admin->generateUrl('list');
  373. }
  374. if (null !== $this->get('request')->get('btn_create_and_create')) {
  375. $params = array();
  376. if ($this->admin->hasActiveSubClass()) {
  377. $params['subclass'] = $this->get('request')->get('subclass');
  378. }
  379. $url = $this->admin->generateUrl('create', $params);
  380. }
  381. if ($this->getRestMethod() == 'DELETE') {
  382. $url = $this->admin->generateUrl('list');
  383. }
  384. if (!$url) {
  385. $url = $this->admin->generateObjectUrl('edit', $object);
  386. }
  387. return new RedirectResponse($url);
  388. }
  389. /**
  390. * Batch action
  391. *
  392. * @return Response|RedirectResponse
  393. *
  394. * @throws NotFoundHttpException If the HTTP method is not POST
  395. * @throws \RuntimeException If the batch action is not defined
  396. */
  397. public function batchAction()
  398. {
  399. $restMethod = $this->getRestMethod();
  400. if ('POST' !== $restMethod) {
  401. throw $this->createNotFoundException(sprintf('Invalid request type "%s", POST expected', $restMethod));
  402. }
  403. // check the csrf token
  404. $this->validateCsrfToken('sonata.batch');
  405. $confirmation = $this->get('request')->get('confirmation', false);
  406. if ($data = json_decode($this->get('request')->get('data'), true)) {
  407. $action = $data['action'];
  408. $idx = $data['idx'];
  409. $allElements = $data['all_elements'];
  410. $this->get('request')->request->replace($data);
  411. } else {
  412. $this->get('request')->request->set('idx', $this->get('request')->get('idx', array()));
  413. $this->get('request')->request->set('all_elements', $this->get('request')->get('all_elements', false));
  414. $action = $this->get('request')->get('action');
  415. $idx = $this->get('request')->get('idx');
  416. $allElements = $this->get('request')->get('all_elements');
  417. $data = $this->get('request')->request->all();
  418. unset($data['_sonata_csrf_token']);
  419. }
  420. $batchActions = $this->admin->getBatchActions();
  421. if (!array_key_exists($action, $batchActions)) {
  422. throw new \RuntimeException(sprintf('The `%s` batch action is not defined', $action));
  423. }
  424. $camelizedAction = BaseFieldDescription::camelize($action);
  425. $isRelevantAction = sprintf('batchAction%sIsRelevant', ucfirst($camelizedAction));
  426. if (method_exists($this, $isRelevantAction)) {
  427. $nonRelevantMessage = call_user_func(array($this, $isRelevantAction), $idx, $allElements);
  428. } else {
  429. $nonRelevantMessage = count($idx) != 0 || $allElements; // at least one item is selected
  430. }
  431. if (!$nonRelevantMessage) { // default non relevant message (if false of null)
  432. $nonRelevantMessage = 'flash_batch_empty';
  433. }
  434. $datagrid = $this->admin->getDatagrid();
  435. $datagrid->buildPager();
  436. if (true !== $nonRelevantMessage) {
  437. $this->addFlash('sonata_flash_info', $nonRelevantMessage);
  438. return new RedirectResponse(
  439. $this->admin->generateUrl(
  440. 'list',
  441. array('filter' => $this->admin->getFilterParameters())
  442. )
  443. );
  444. }
  445. $askConfirmation = isset($batchActions[$action]['ask_confirmation']) ?
  446. $batchActions[$action]['ask_confirmation'] :
  447. true;
  448. if ($askConfirmation && $confirmation != 'ok') {
  449. $actionLabel = $batchActions[$action]['label'];
  450. $formView = $datagrid->getForm()->createView();
  451. return $this->render($this->admin->getTemplate('batch_confirmation'), array(
  452. 'action' => 'list',
  453. 'action_label' => $actionLabel,
  454. 'datagrid' => $datagrid,
  455. 'form' => $formView,
  456. 'data' => $data,
  457. 'csrf_token' => $this->getCsrfToken('sonata.batch'),
  458. ));
  459. }
  460. // execute the action, batchActionXxxxx
  461. $finalAction = sprintf('batchAction%s', ucfirst($camelizedAction));
  462. if (!method_exists($this, $finalAction)) {
  463. throw new \RuntimeException(sprintf('A `%s::%s` method must be created', get_class($this), $finalAction));
  464. }
  465. $query = $datagrid->getQuery();
  466. $query->setFirstResult(null);
  467. $query->setMaxResults(null);
  468. $this->admin->preBatchAction($action, $query, $idx, $allElements);
  469. if (count($idx) > 0) {
  470. $this->admin->getModelManager()->addIdentifiersToQuery($this->admin->getClass(), $query, $idx);
  471. } elseif (!$allElements) {
  472. $query = null;
  473. }
  474. return call_user_func(array($this, $finalAction), $query);
  475. }
  476. /**
  477. * Create action
  478. *
  479. * @return Response
  480. *
  481. * @throws AccessDeniedException If access is not granted
  482. */
  483. public function createAction()
  484. {
  485. // the key used to lookup the template
  486. $templateKey = 'edit';
  487. if (false === $this->admin->isGranted('CREATE')) {
  488. throw new AccessDeniedException();
  489. }
  490. $object = $this->admin->getNewInstance();
  491. $this->admin->setSubject($object);
  492. /** @var $form \Symfony\Component\Form\Form */
  493. $form = $this->admin->getForm();
  494. $form->setData($object);
  495. if ($this->getRestMethod()== 'POST') {
  496. $form->submit($this->get('request'));
  497. $isFormValid = $form->isValid();
  498. // persist if the form was valid and if in preview mode the preview was approved
  499. if ($isFormValid && (!$this->isInPreviewMode() || $this->isPreviewApproved())) {
  500. if (false === $this->admin->isGranted('CREATE', $object)) {
  501. throw new AccessDeniedException();
  502. }
  503. try {
  504. $object = $this->admin->create($object);
  505. if ($this->isXmlHttpRequest()) {
  506. return $this->renderJson(array(
  507. 'result' => 'ok',
  508. 'objectId' => $this->admin->getNormalizedIdentifier($object)
  509. ));
  510. }
  511. $this->addFlash(
  512. 'sonata_flash_success',
  513. $this->admin->trans(
  514. 'flash_create_success',
  515. array('%name%' => $this->admin->toString($object)),
  516. 'SonataAdminBundle'
  517. )
  518. );
  519. // redirect to edit mode
  520. return $this->redirectTo($object);
  521. } catch (ModelManagerException $e) {
  522. $this->logModelManagerException($e);
  523. $isFormValid = false;
  524. }
  525. }
  526. // show an error message if the form failed validation
  527. if (!$isFormValid) {
  528. if (!$this->isXmlHttpRequest()) {
  529. $this->addFlash(
  530. 'sonata_flash_error',
  531. $this->admin->trans(
  532. 'flash_create_error',
  533. array('%name%' => $this->admin->toString($object)),
  534. 'SonataAdminBundle'
  535. )
  536. );
  537. }
  538. } elseif ($this->isPreviewRequested()) {
  539. // pick the preview template if the form was valid and preview was requested
  540. $templateKey = 'preview';
  541. $this->admin->getShow();
  542. }
  543. }
  544. $view = $form->createView();
  545. // set the theme for the current Admin Form
  546. $this->get('twig')->getExtension('form')->renderer->setTheme($view, $this->admin->getFormTheme());
  547. return $this->render($this->admin->getTemplate($templateKey), array(
  548. 'action' => 'create',
  549. 'form' => $view,
  550. 'object' => $object,
  551. ));
  552. }
  553. /**
  554. * Returns true if the preview is requested to be shown
  555. *
  556. * @return bool
  557. */
  558. protected function isPreviewRequested()
  559. {
  560. return ($this->get('request')->get('btn_preview') !== null);
  561. }
  562. /**
  563. * Returns true if the preview has been approved
  564. *
  565. * @return bool
  566. */
  567. protected function isPreviewApproved()
  568. {
  569. return ($this->get('request')->get('btn_preview_approve') !== null);
  570. }
  571. /**
  572. * Returns true if the request is in the preview workflow
  573. *
  574. * That means either a preview is requested or the preview has already been shown
  575. * and it got approved/declined.
  576. *
  577. * @return bool
  578. */
  579. protected function isInPreviewMode()
  580. {
  581. return $this->admin->supportsPreviewMode()
  582. && ($this->isPreviewRequested()
  583. || $this->isPreviewApproved()
  584. || $this->isPreviewDeclined());
  585. }
  586. /**
  587. * Returns true if the preview has been declined
  588. *
  589. * @return bool
  590. */
  591. protected function isPreviewDeclined()
  592. {
  593. return ($this->get('request')->get('btn_preview_decline') !== null);
  594. }
  595. /**
  596. * Show action
  597. *
  598. * @param int|string|null $id
  599. *
  600. * @return Response
  601. *
  602. * @throws NotFoundHttpException If the object does not exist
  603. * @throws AccessDeniedException If access is not granted
  604. */
  605. public function showAction($id = null)
  606. {
  607. $id = $this->get('request')->get($this->admin->getIdParameter());
  608. $object = $this->admin->getObject($id);
  609. if (!$object) {
  610. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  611. }
  612. if (false === $this->admin->isGranted('VIEW', $object)) {
  613. throw new AccessDeniedException();
  614. }
  615. $this->admin->setSubject($object);
  616. return $this->render($this->admin->getTemplate('show'), array(
  617. 'action' => 'show',
  618. 'object' => $object,
  619. 'elements' => $this->admin->getShow(),
  620. ));
  621. }
  622. /**
  623. * Show history revisions for object
  624. *
  625. * @param int|string|null $id
  626. *
  627. * @return Response
  628. *
  629. * @throws AccessDeniedException If access is not granted
  630. * @throws NotFoundHttpException If the object does not exist or the audit reader is not available
  631. */
  632. public function historyAction($id = null)
  633. {
  634. $id = $this->get('request')->get($this->admin->getIdParameter());
  635. $object = $this->admin->getObject($id);
  636. if (!$object) {
  637. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  638. }
  639. if (false === $this->admin->isGranted('EDIT', $object)) {
  640. throw new AccessDeniedException();
  641. }
  642. $manager = $this->get('sonata.admin.audit.manager');
  643. if (!$manager->hasReader($this->admin->getClass())) {
  644. throw new NotFoundHttpException(
  645. sprintf(
  646. 'unable to find the audit reader for class : %s',
  647. $this->admin->getClass()
  648. )
  649. );
  650. }
  651. $reader = $manager->getReader($this->admin->getClass());
  652. $revisions = $reader->findRevisions($this->admin->getClass(), $id);
  653. return $this->render($this->admin->getTemplate('history'), array(
  654. 'action' => 'history',
  655. 'object' => $object,
  656. 'revisions' => $revisions,
  657. 'currentRevision' => $revisions ? current($revisions) : false,
  658. ));
  659. }
  660. /**
  661. * View history revision of object
  662. *
  663. * @param int|string|null $id
  664. * @param string|null $revision
  665. *
  666. * @return Response
  667. *
  668. * @throws AccessDeniedException If access is not granted
  669. * @throws NotFoundHttpException If the object or revision does not exist or the audit reader is not available
  670. */
  671. public function historyViewRevisionAction($id = null, $revision = null)
  672. {
  673. $id = $this->get('request')->get($this->admin->getIdParameter());
  674. $object = $this->admin->getObject($id);
  675. if (!$object) {
  676. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  677. }
  678. if (false === $this->admin->isGranted('EDIT', $object)) {
  679. throw new AccessDeniedException();
  680. }
  681. $manager = $this->get('sonata.admin.audit.manager');
  682. if (!$manager->hasReader($this->admin->getClass())) {
  683. throw new NotFoundHttpException(
  684. sprintf(
  685. 'unable to find the audit reader for class : %s',
  686. $this->admin->getClass()
  687. )
  688. );
  689. }
  690. $reader = $manager->getReader($this->admin->getClass());
  691. // retrieve the revisioned object
  692. $object = $reader->find($this->admin->getClass(), $id, $revision);
  693. if (!$object) {
  694. throw new NotFoundHttpException(
  695. sprintf(
  696. 'unable to find the targeted object `%s` from the revision `%s` with classname : `%s`',
  697. $id,
  698. $revision,
  699. $this->admin->getClass()
  700. )
  701. );
  702. }
  703. $this->admin->setSubject($object);
  704. return $this->render($this->admin->getTemplate('show'), array(
  705. 'action' => 'show',
  706. 'object' => $object,
  707. 'elements' => $this->admin->getShow(),
  708. ));
  709. }
  710. /**
  711. * Compare history revisions of object
  712. *
  713. * @param int|string|null $id
  714. * @param int|string|null $base_revision
  715. * @param int|string|null $compare_revision
  716. *
  717. * @return Response
  718. *
  719. * @throws AccessDeniedException If access is not granted
  720. * @throws NotFoundHttpException If the object or revision does not exist or the audit reader is not available
  721. */
  722. public function historyCompareRevisionsAction($id = null, $base_revision = null, $compare_revision = null)
  723. {
  724. if (false === $this->admin->isGranted('EDIT')) {
  725. throw new AccessDeniedException();
  726. }
  727. $id = $this->get('request')->get($this->admin->getIdParameter());
  728. $object = $this->admin->getObject($id);
  729. if (!$object) {
  730. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  731. }
  732. $manager = $this->get('sonata.admin.audit.manager');
  733. if (!$manager->hasReader($this->admin->getClass())) {
  734. throw new NotFoundHttpException(
  735. sprintf(
  736. 'unable to find the audit reader for class : %s',
  737. $this->admin->getClass()
  738. )
  739. );
  740. }
  741. $reader = $manager->getReader($this->admin->getClass());
  742. // retrieve the base revision
  743. $base_object = $reader->find($this->admin->getClass(), $id, $base_revision);
  744. if (!$base_object) {
  745. throw new NotFoundHttpException(
  746. sprintf(
  747. 'unable to find the targeted object `%s` from the revision `%s` with classname : `%s`',
  748. $id,
  749. $base_revision,
  750. $this->admin->getClass()
  751. )
  752. );
  753. }
  754. // retrieve the compare revision
  755. $compare_object = $reader->find($this->admin->getClass(), $id, $compare_revision);
  756. if (!$compare_object) {
  757. throw new NotFoundHttpException(
  758. sprintf(
  759. 'unable to find the targeted object `%s` from the revision `%s` with classname : `%s`',
  760. $id,
  761. $compare_revision,
  762. $this->admin->getClass()
  763. )
  764. );
  765. }
  766. $this->admin->setSubject($base_object);
  767. return $this->render($this->admin->getTemplate('show_compare'), array(
  768. 'action' => 'show',
  769. 'object' => $base_object,
  770. 'object_compare' => $compare_object,
  771. 'elements' => $this->admin->getShow()
  772. ));
  773. }
  774. /**
  775. * Export data to specified format
  776. *
  777. * @param Request $request
  778. *
  779. * @return Response
  780. *
  781. * @throws AccessDeniedException If access is not granted
  782. * @throws \RuntimeException If the export format is invalid
  783. */
  784. public function exportAction(Request $request)
  785. {
  786. if (false === $this->admin->isGranted('EXPORT')) {
  787. throw new AccessDeniedException();
  788. }
  789. $format = $request->get('format');
  790. $allowedExportFormats = (array) $this->admin->getExportFormats();
  791. if (!in_array($format, $allowedExportFormats)) {
  792. throw new \RuntimeException(
  793. sprintf(
  794. 'Export in format `%s` is not allowed for class: `%s`. Allowed formats are: `%s`',
  795. $format,
  796. $this->admin->getClass(),
  797. implode(', ', $allowedExportFormats)
  798. )
  799. );
  800. }
  801. $filename = sprintf(
  802. 'export_%s_%s.%s',
  803. strtolower(substr($this->admin->getClass(), strripos($this->admin->getClass(), '\\') + 1)),
  804. date('Y_m_d_H_i_s', strtotime('now')),
  805. $format
  806. );
  807. return $this->get('sonata.admin.exporter')->getResponse(
  808. $format,
  809. $filename,
  810. $this->admin->getDataSourceIterator()
  811. );
  812. }
  813. /**
  814. * Gets ACL users
  815. *
  816. * @return \Traversable
  817. */
  818. protected function getAclUsers()
  819. {
  820. $aclUsers = array();
  821. $userManagerServiceName = $this->container->getParameter('sonata.admin.security.acl_user_manager');
  822. if ($userManagerServiceName !== null && $this->has($userManagerServiceName)) {
  823. $userManager = $this->get($userManagerServiceName);
  824. if (method_exists($userManager, 'findUsers')) {
  825. $aclUsers = $userManager->findUsers();
  826. }
  827. }
  828. return is_array($aclUsers) ? new \ArrayIterator($aclUsers) : $aclUsers;
  829. }
  830. /**
  831. * Returns the Response object associated to the acl action
  832. *
  833. * @param int|string|null $id
  834. *
  835. * @return Response|RedirectResponse
  836. *
  837. * @throws AccessDeniedException If access is not granted.
  838. * @throws NotFoundHttpException If the object does not exist or the ACL is not enabled
  839. */
  840. public function aclAction($id = null)
  841. {
  842. if (!$this->admin->isAclEnabled()) {
  843. throw new NotFoundHttpException('ACL are not enabled for this admin');
  844. }
  845. $id = $this->get('request')->get($this->admin->getIdParameter());
  846. $object = $this->admin->getObject($id);
  847. if (!$object) {
  848. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  849. }
  850. if (false === $this->admin->isGranted('MASTER', $object)) {
  851. throw new AccessDeniedException();
  852. }
  853. $this->admin->setSubject($object);
  854. $aclUsers = $this->getAclUsers();
  855. $adminObjectAclManipulator = $this->get('sonata.admin.object.manipulator.acl.admin');
  856. $adminObjectAclData = new AdminObjectAclData(
  857. $this->admin,
  858. $object,
  859. $aclUsers,
  860. $adminObjectAclManipulator->getMaskBuilderClass()
  861. );
  862. $form = $adminObjectAclManipulator->createForm($adminObjectAclData);
  863. $request = $this->getRequest();
  864. if ($request->getMethod() === 'POST') {
  865. $form->submit($request);
  866. if ($form->isValid()) {
  867. $adminObjectAclManipulator->updateAcl($adminObjectAclData);
  868. $this->addFlash('sonata_flash_success', 'flash_acl_edit_success');
  869. return new RedirectResponse($this->admin->generateObjectUrl('acl', $object));
  870. }
  871. }
  872. return $this->render($this->admin->getTemplate('acl'), array(
  873. 'action' => 'acl',
  874. 'permissions' => $adminObjectAclData->getUserPermissions(),
  875. 'object' => $object,
  876. 'users' => $aclUsers,
  877. 'form' => $form->createView()
  878. ));
  879. }
  880. /**
  881. * Adds a flash message for type.
  882. *
  883. * @param string $type
  884. * @param string $message
  885. */
  886. protected function addFlash($type, $message)
  887. {
  888. $this->get('session')
  889. ->getFlashBag()
  890. ->add($type, $message);
  891. }
  892. /**
  893. * Validate CSRF token for action without form
  894. *
  895. * @param string $intention
  896. *
  897. * @throws HttpException
  898. */
  899. protected function validateCsrfToken($intention)
  900. {
  901. if (!$this->container->has('form.csrf_provider')) {
  902. return;
  903. }
  904. if (!$this->container->get('form.csrf_provider')->isCsrfTokenValid(
  905. $intention,
  906. $this->get('request')->request->get('_sonata_csrf_token', false)
  907. )) {
  908. throw new HttpException(400, 'The csrf token is not valid, CSRF attack?');
  909. }
  910. }
  911. /**
  912. * Get CSRF token
  913. *
  914. * @param string $intention
  915. *
  916. * @return string|false
  917. */
  918. protected function getCsrfToken($intention)
  919. {
  920. if (!$this->container->has('form.csrf_provider')) {
  921. return false;
  922. }
  923. return $this->container->get('form.csrf_provider')->generateCsrfToken($intention);
  924. }
  925. }