CRUDController.php 36 KB

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