CRUDController.php 35 KB

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