CRUDController.php 41 KB

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