CRUDController.php 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375
  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. $preResponse = $this->preList($request);
  213. if ($preResponse !== null) {
  214. return $preResponse;
  215. }
  216. if ($listMode = $request->get('_list_mode')) {
  217. $this->admin->setListMode($listMode);
  218. }
  219. $datagrid = $this->admin->getDatagrid();
  220. $formView = $datagrid->getForm()->createView();
  221. // set the theme for the current Admin Form
  222. $this->get('twig')->getExtension('form')->renderer->setTheme($formView, $this->admin->getFilterTheme());
  223. return $this->render($this->admin->getTemplate('list'), array(
  224. 'action' => 'list',
  225. 'form' => $formView,
  226. 'datagrid' => $datagrid,
  227. 'csrf_token' => $this->getCsrfToken('sonata.batch'),
  228. ), null, $request);
  229. }
  230. /**
  231. * Execute a batch delete
  232. *
  233. * @param ProxyQueryInterface $query
  234. *
  235. * @return RedirectResponse
  236. *
  237. * @throws AccessDeniedException If access is not granted
  238. */
  239. public function batchActionDelete(ProxyQueryInterface $query)
  240. {
  241. if (false === $this->admin->isGranted('DELETE')) {
  242. throw new AccessDeniedException();
  243. }
  244. $modelManager = $this->admin->getModelManager();
  245. try {
  246. $modelManager->batchDelete($this->admin->getClass(), $query);
  247. $this->addFlash('sonata_flash_success', 'flash_batch_delete_success');
  248. } catch (ModelManagerException $e) {
  249. $this->handleModelManagerException($e);
  250. $this->addFlash('sonata_flash_error', 'flash_batch_delete_error');
  251. }
  252. return new RedirectResponse($this->admin->generateUrl(
  253. 'list',
  254. array('filter' => $this->admin->getFilterParameters())
  255. ));
  256. }
  257. /**
  258. * Delete action
  259. *
  260. * @param int|string|null $id
  261. * @param Request $request
  262. *
  263. * @return Response|RedirectResponse
  264. *
  265. * @throws NotFoundHttpException If the object does not exist
  266. * @throws AccessDeniedException If access is not granted
  267. */
  268. public function deleteAction($id, Request $request = null)
  269. {
  270. $request = $this->resolveRequest($request);
  271. $id = $request->get($this->admin->getIdParameter());
  272. $object = $this->admin->getObject($id);
  273. if (!$object) {
  274. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  275. }
  276. if (false === $this->admin->isGranted('DELETE', $object)) {
  277. throw new AccessDeniedException();
  278. }
  279. $preResponse = $this->preDelete($request, $object);
  280. if ($preResponse !== null) {
  281. return $preResponse;
  282. }
  283. if ($this->getRestMethod($request) === 'DELETE') {
  284. // check the csrf token
  285. $this->validateCsrfToken('sonata.delete', $request);
  286. $objectName = $this->admin->toString($object);
  287. try {
  288. $this->admin->delete($object);
  289. if ($this->isXmlHttpRequest($request)) {
  290. return $this->renderJson(array('result' => 'ok'), 200, array(), $request);
  291. }
  292. $this->addFlash(
  293. 'sonata_flash_success',
  294. $this->admin->trans(
  295. 'flash_delete_success',
  296. array('%name%' => $this->escapeHtml($objectName)),
  297. 'SonataAdminBundle'
  298. )
  299. );
  300. } catch (ModelManagerException $e) {
  301. $this->handleModelManagerException($e);
  302. if ($this->isXmlHttpRequest($request)) {
  303. return $this->renderJson(array('result' => 'error'), 200, array(), $request);
  304. }
  305. $this->addFlash(
  306. 'sonata_flash_error',
  307. $this->admin->trans(
  308. 'flash_delete_error',
  309. array('%name%' => $this->escapeHtml($objectName)),
  310. 'SonataAdminBundle'
  311. )
  312. );
  313. }
  314. return $this->redirectTo($object, $request);
  315. }
  316. return $this->render($this->admin->getTemplate('delete'), array(
  317. 'object' => $object,
  318. 'action' => 'delete',
  319. 'csrf_token' => $this->getCsrfToken('sonata.delete'),
  320. ), null, $request);
  321. }
  322. /**
  323. * Edit action
  324. *
  325. * @param int|string|null $id
  326. * @param Request $request
  327. *
  328. * @return Response|RedirectResponse
  329. *
  330. * @throws NotFoundHttpException If the object does not exist
  331. * @throws AccessDeniedException If access is not granted
  332. */
  333. public function editAction($id = null, Request $request = null)
  334. {
  335. $request = $this->resolveRequest($request);
  336. // the key used to lookup the template
  337. $templateKey = 'edit';
  338. $id = $request->get($this->admin->getIdParameter());
  339. $object = $this->admin->getObject($id);
  340. if (!$object) {
  341. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  342. }
  343. if (false === $this->admin->isGranted('EDIT', $object)) {
  344. throw new AccessDeniedException();
  345. }
  346. $preResponse = $this->preEdit($request, $object);
  347. if ($preResponse !== null) {
  348. return $preResponse;
  349. }
  350. $this->admin->setSubject($object);
  351. /** @var $form \Symfony\Component\Form\Form */
  352. $form = $this->admin->getForm();
  353. $form->setData($object);
  354. $form->handleRequest($request);
  355. if ($form->isSubmitted()) {
  356. $isFormValid = $form->isValid();
  357. // persist if the form was valid and if in preview mode the preview was approved
  358. if ($isFormValid && (!$this->isInPreviewMode($request) || $this->isPreviewApproved($request))) {
  359. try {
  360. $object = $this->admin->update($object);
  361. if ($this->isXmlHttpRequest($request)) {
  362. return $this->renderJson(array(
  363. 'result' => 'ok',
  364. 'objectId' => $this->admin->getNormalizedIdentifier($object),
  365. ), 200, array(), $request);
  366. }
  367. $this->addFlash(
  368. 'sonata_flash_success',
  369. $this->admin->trans(
  370. 'flash_edit_success',
  371. array('%name%' => $this->escapeHtml($this->admin->toString($object))),
  372. 'SonataAdminBundle'
  373. )
  374. );
  375. // redirect to edit mode
  376. return $this->redirectTo($object, $request);
  377. } catch (ModelManagerException $e) {
  378. $this->handleModelManagerException($e);
  379. $isFormValid = false;
  380. }
  381. }
  382. // show an error message if the form failed validation
  383. if (!$isFormValid) {
  384. if (!$this->isXmlHttpRequest($request)) {
  385. $this->addFlash(
  386. 'sonata_flash_error',
  387. $this->admin->trans(
  388. 'flash_edit_error',
  389. array('%name%' => $this->escapeHtml($this->admin->toString($object))),
  390. 'SonataAdminBundle'
  391. )
  392. );
  393. }
  394. } elseif ($this->isPreviewRequested($request)) {
  395. // enable the preview template if the form was valid and preview was requested
  396. $templateKey = 'preview';
  397. $this->admin->getShow();
  398. }
  399. }
  400. $view = $form->createView();
  401. // set the theme for the current Admin Form
  402. $this->get('twig')->getExtension('form')->renderer->setTheme($view, $this->admin->getFormTheme());
  403. return $this->render($this->admin->getTemplate($templateKey), array(
  404. 'action' => 'edit',
  405. 'form' => $view,
  406. 'object' => $object,
  407. ), null, $request);
  408. }
  409. /**
  410. * Redirect the user depend on this choice
  411. *
  412. * @param object $object
  413. * @param Request $request
  414. *
  415. * @return RedirectResponse
  416. */
  417. protected function redirectTo($object, Request $request = null)
  418. {
  419. $request = $this->resolveRequest($request);
  420. $url = false;
  421. if (null !== $request->get('btn_update_and_list')) {
  422. $url = $this->admin->generateUrl('list');
  423. }
  424. if (null !== $request->get('btn_create_and_list')) {
  425. $url = $this->admin->generateUrl('list');
  426. }
  427. if (null !== $request->get('btn_create_and_create')) {
  428. $params = array();
  429. if ($this->admin->hasActiveSubClass()) {
  430. $params['subclass'] = $request->get('subclass');
  431. }
  432. $url = $this->admin->generateUrl('create', $params);
  433. }
  434. if ($this->getRestMethod($request) === 'DELETE') {
  435. $url = $this->admin->generateUrl('list');
  436. }
  437. if (!$url) {
  438. $url = $this->admin->generateObjectUrl('edit', $object);
  439. }
  440. return new RedirectResponse($url);
  441. }
  442. /**
  443. * Batch action
  444. *
  445. * @param Request $request
  446. *
  447. * @return Response|RedirectResponse
  448. *
  449. * @throws NotFoundHttpException If the HTTP method is not POST
  450. * @throws \RuntimeException If the batch action is not defined
  451. */
  452. public function batchAction(Request $request = null)
  453. {
  454. $request = $this->resolveRequest($request);
  455. $restMethod = $this->getRestMethod($request);
  456. if ('POST' !== $restMethod) {
  457. throw $this->createNotFoundException(sprintf('Invalid request type "%s", POST expected', $restMethod));
  458. }
  459. // check the csrf token
  460. $this->validateCsrfToken('sonata.batch', $request);
  461. $confirmation = $request->get('confirmation', false);
  462. if ($data = json_decode($request->get('data'), true)) {
  463. $action = $data['action'];
  464. $idx = $data['idx'];
  465. $allElements = $data['all_elements'];
  466. $request->request->replace($data);
  467. } else {
  468. $request->request->set('idx', $request->get('idx', array()));
  469. $request->request->set('all_elements', $request->get('all_elements', false));
  470. $action = $request->get('action');
  471. $idx = $request->get('idx');
  472. $allElements = $request->get('all_elements');
  473. $data = $request->request->all();
  474. unset($data['_sonata_csrf_token']);
  475. }
  476. $batchActions = $this->admin->getBatchActions();
  477. if (!array_key_exists($action, $batchActions)) {
  478. throw new \RuntimeException(sprintf('The `%s` batch action is not defined', $action));
  479. }
  480. $camelizedAction = BaseFieldDescription::camelize($action);
  481. $isRelevantAction = sprintf('batchAction%sIsRelevant', ucfirst($camelizedAction));
  482. if (method_exists($this, $isRelevantAction)) {
  483. $nonRelevantMessage = call_user_func(array($this, $isRelevantAction), $idx, $allElements);
  484. } else {
  485. $nonRelevantMessage = count($idx) != 0 || $allElements; // at least one item is selected
  486. }
  487. if (!$nonRelevantMessage) { // default non relevant message (if false of null)
  488. $nonRelevantMessage = 'flash_batch_empty';
  489. }
  490. $datagrid = $this->admin->getDatagrid();
  491. $datagrid->buildPager();
  492. if (true !== $nonRelevantMessage) {
  493. $this->addFlash('sonata_flash_info', $nonRelevantMessage);
  494. return new RedirectResponse(
  495. $this->admin->generateUrl(
  496. 'list',
  497. array('filter' => $this->admin->getFilterParameters())
  498. )
  499. );
  500. }
  501. $askConfirmation = isset($batchActions[$action]['ask_confirmation']) ?
  502. $batchActions[$action]['ask_confirmation'] :
  503. true;
  504. if ($askConfirmation && $confirmation != 'ok') {
  505. $actionLabel = $batchActions[$action]['label'];
  506. $formView = $datagrid->getForm()->createView();
  507. return $this->render($this->admin->getTemplate('batch_confirmation'), array(
  508. 'action' => 'list',
  509. 'action_label' => $actionLabel,
  510. 'datagrid' => $datagrid,
  511. 'form' => $formView,
  512. 'data' => $data,
  513. 'csrf_token' => $this->getCsrfToken('sonata.batch'),
  514. ), null, $request);
  515. }
  516. // execute the action, batchActionXxxxx
  517. $finalAction = sprintf('batchAction%s', ucfirst($camelizedAction));
  518. if (!is_callable(array($this, $finalAction))) {
  519. throw new \RuntimeException(sprintf('A `%s::%s` method must be callable', get_class($this), $finalAction));
  520. }
  521. $query = $datagrid->getQuery();
  522. $query->setFirstResult(null);
  523. $query->setMaxResults(null);
  524. $this->admin->preBatchAction($action, $query, $idx, $allElements);
  525. if (count($idx) > 0) {
  526. $this->admin->getModelManager()->addIdentifiersToQuery($this->admin->getClass(), $query, $idx);
  527. } elseif (!$allElements) {
  528. $query = null;
  529. }
  530. return call_user_func(array($this, $finalAction), $query);
  531. }
  532. /**
  533. * Create action
  534. *
  535. * @param Request $request
  536. *
  537. * @return Response
  538. *
  539. * @throws AccessDeniedException If access is not granted
  540. */
  541. public function createAction(Request $request = null)
  542. {
  543. $request = $this->resolveRequest($request);
  544. // the key used to lookup the template
  545. $templateKey = 'edit';
  546. if (false === $this->admin->isGranted('CREATE')) {
  547. throw new AccessDeniedException();
  548. }
  549. $class = new \ReflectionClass($this->admin->hasActiveSubClass() ? $this->admin->getActiveSubClass() : $this->admin->getClass());
  550. if ($class->isAbstract()) {
  551. return $this->render(
  552. 'SonataAdminBundle:CRUD:select_subclass.html.twig',
  553. array(
  554. 'base_template' => $this->getBaseTemplate(),
  555. 'admin' => $this->admin,
  556. 'action' => 'create',
  557. ),
  558. null,
  559. $request
  560. );
  561. }
  562. $object = $this->admin->getNewInstance();
  563. $preResponse = $this->preCreate($request, $object);
  564. if ($preResponse !== null) {
  565. return $preResponse;
  566. }
  567. $this->admin->setSubject($object);
  568. /** @var $form \Symfony\Component\Form\Form */
  569. $form = $this->admin->getForm();
  570. $form->setData($object);
  571. $form->handleRequest($request);
  572. if ($form->isSubmitted()) {
  573. $isFormValid = $form->isValid();
  574. // persist if the form was valid and if in preview mode the preview was approved
  575. if ($isFormValid && (!$this->isInPreviewMode($request) || $this->isPreviewApproved($request))) {
  576. if (false === $this->admin->isGranted('CREATE', $object)) {
  577. throw new AccessDeniedException();
  578. }
  579. try {
  580. $object = $this->admin->create($object);
  581. if ($this->isXmlHttpRequest($request)) {
  582. return $this->renderJson(array(
  583. 'result' => 'ok',
  584. 'objectId' => $this->admin->getNormalizedIdentifier($object),
  585. ), 200, array(), $request);
  586. }
  587. $this->addFlash(
  588. 'sonata_flash_success',
  589. $this->admin->trans(
  590. 'flash_create_success',
  591. array('%name%' => $this->escapeHtml($this->admin->toString($object))),
  592. 'SonataAdminBundle'
  593. )
  594. );
  595. // redirect to edit mode
  596. return $this->redirectTo($object, $request);
  597. } catch (ModelManagerException $e) {
  598. $this->handleModelManagerException($e);
  599. $isFormValid = false;
  600. }
  601. }
  602. // show an error message if the form failed validation
  603. if (!$isFormValid) {
  604. if (!$this->isXmlHttpRequest($request)) {
  605. $this->addFlash(
  606. 'sonata_flash_error',
  607. $this->admin->trans(
  608. 'flash_create_error',
  609. array('%name%' => $this->escapeHtml($this->admin->toString($object))),
  610. 'SonataAdminBundle'
  611. )
  612. );
  613. }
  614. } elseif ($this->isPreviewRequested($request)) {
  615. // pick the preview template if the form was valid and preview was requested
  616. $templateKey = 'preview';
  617. $this->admin->getShow();
  618. }
  619. }
  620. $view = $form->createView();
  621. // set the theme for the current Admin Form
  622. $this->get('twig')->getExtension('form')->renderer->setTheme($view, $this->admin->getFormTheme());
  623. return $this->render($this->admin->getTemplate($templateKey), array(
  624. 'action' => 'create',
  625. 'form' => $view,
  626. 'object' => $object,
  627. ), null, $request);
  628. }
  629. /**
  630. * Returns true if the preview is requested to be shown
  631. *
  632. * @param Request $request
  633. *
  634. * @return bool
  635. */
  636. protected function isPreviewRequested(Request $request = null)
  637. {
  638. $request = $this->resolveRequest($request);
  639. return ($request->get('btn_preview') !== null);
  640. }
  641. /**
  642. * Returns true if the preview has been approved
  643. *
  644. * @param Request $request
  645. *
  646. * @return bool
  647. */
  648. protected function isPreviewApproved(Request $request = null)
  649. {
  650. $request = $this->resolveRequest($request);
  651. return ($request->get('btn_preview_approve') !== null);
  652. }
  653. /**
  654. * Returns true if the request is in the preview workflow
  655. *
  656. * That means either a preview is requested or the preview has already been shown
  657. * and it got approved/declined.
  658. *
  659. * @param Request $request
  660. *
  661. * @return bool
  662. */
  663. protected function isInPreviewMode(Request $request = null)
  664. {
  665. $request = $this->resolveRequest($request);
  666. return $this->admin->supportsPreviewMode()
  667. && ($this->isPreviewRequested($request)
  668. || $this->isPreviewApproved($request)
  669. || $this->isPreviewDeclined($request));
  670. }
  671. /**
  672. * Returns true if the preview has been declined
  673. *
  674. * @param Request $request
  675. *
  676. * @return bool
  677. */
  678. protected function isPreviewDeclined(Request $request = null)
  679. {
  680. $request = $this->resolveRequest($request);
  681. return ($request->get('btn_preview_decline') !== null);
  682. }
  683. /**
  684. * Show action
  685. *
  686. * @param int|string|null $id
  687. * @param Request $request
  688. *
  689. * @return Response
  690. *
  691. * @throws NotFoundHttpException If the object does not exist
  692. * @throws AccessDeniedException If access is not granted
  693. */
  694. public function showAction($id = null, Request $request = null)
  695. {
  696. $request = $this->resolveRequest($request);
  697. $id = $request->get($this->admin->getIdParameter());
  698. $object = $this->admin->getObject($id);
  699. if (!$object) {
  700. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  701. }
  702. if (false === $this->admin->isGranted('VIEW', $object)) {
  703. throw new AccessDeniedException();
  704. }
  705. $preResponse = $this->preShow($request, $object);
  706. if ($preResponse !== null) {
  707. return $preResponse;
  708. }
  709. $this->admin->setSubject($object);
  710. return $this->render($this->admin->getTemplate('show'), array(
  711. 'action' => 'show',
  712. 'object' => $object,
  713. 'elements' => $this->admin->getShow(),
  714. ), null, $request);
  715. }
  716. /**
  717. * Show history revisions for object
  718. *
  719. * @param int|string|null $id
  720. * @param Request $request
  721. *
  722. * @return Response
  723. *
  724. * @throws AccessDeniedException If access is not granted
  725. * @throws NotFoundHttpException If the object does not exist or the audit reader is not available
  726. */
  727. public function historyAction($id = null, Request $request = null)
  728. {
  729. $request = $this->resolveRequest($request);
  730. $id = $request->get($this->admin->getIdParameter());
  731. $object = $this->admin->getObject($id);
  732. if (!$object) {
  733. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  734. }
  735. if (false === $this->admin->isGranted('EDIT', $object)) {
  736. throw new AccessDeniedException();
  737. }
  738. $manager = $this->get('sonata.admin.audit.manager');
  739. if (!$manager->hasReader($this->admin->getClass())) {
  740. throw new NotFoundHttpException(
  741. sprintf(
  742. 'unable to find the audit reader for class : %s',
  743. $this->admin->getClass()
  744. )
  745. );
  746. }
  747. $reader = $manager->getReader($this->admin->getClass());
  748. $revisions = $reader->findRevisions($this->admin->getClass(), $id);
  749. return $this->render($this->admin->getTemplate('history'), array(
  750. 'action' => 'history',
  751. 'object' => $object,
  752. 'revisions' => $revisions,
  753. 'currentRevision' => $revisions ? current($revisions) : false,
  754. ), null, $request);
  755. }
  756. /**
  757. * View history revision of object
  758. *
  759. * @param int|string|null $id
  760. * @param string|null $revision
  761. * @param Request $request
  762. *
  763. * @return Response
  764. *
  765. * @throws AccessDeniedException If access is not granted
  766. * @throws NotFoundHttpException If the object or revision does not exist or the audit reader is not available
  767. */
  768. public function historyViewRevisionAction($id = null, $revision = null, Request $request = null)
  769. {
  770. $request = $this->resolveRequest($request);
  771. $id = $request->get($this->admin->getIdParameter());
  772. $object = $this->admin->getObject($id);
  773. if (!$object) {
  774. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  775. }
  776. if (false === $this->admin->isGranted('EDIT', $object)) {
  777. throw new AccessDeniedException();
  778. }
  779. $manager = $this->get('sonata.admin.audit.manager');
  780. if (!$manager->hasReader($this->admin->getClass())) {
  781. throw new NotFoundHttpException(
  782. sprintf(
  783. 'unable to find the audit reader for class : %s',
  784. $this->admin->getClass()
  785. )
  786. );
  787. }
  788. $reader = $manager->getReader($this->admin->getClass());
  789. // retrieve the revisioned object
  790. $object = $reader->find($this->admin->getClass(), $id, $revision);
  791. if (!$object) {
  792. throw new NotFoundHttpException(
  793. sprintf(
  794. 'unable to find the targeted object `%s` from the revision `%s` with classname : `%s`',
  795. $id,
  796. $revision,
  797. $this->admin->getClass()
  798. )
  799. );
  800. }
  801. $this->admin->setSubject($object);
  802. return $this->render($this->admin->getTemplate('show'), array(
  803. 'action' => 'show',
  804. 'object' => $object,
  805. 'elements' => $this->admin->getShow(),
  806. ), null, $request);
  807. }
  808. /**
  809. * Compare history revisions of object
  810. *
  811. * @param int|string|null $id
  812. * @param int|string|null $base_revision
  813. * @param int|string|null $compare_revision
  814. * @param Request $request
  815. *
  816. * @return Response
  817. *
  818. * @throws AccessDeniedException If access is not granted
  819. * @throws NotFoundHttpException If the object or revision does not exist or the audit reader is not available
  820. */
  821. public function historyCompareRevisionsAction($id = null, $base_revision = null, $compare_revision = null, Request $request = null)
  822. {
  823. $request = $this->resolveRequest($request);
  824. if (false === $this->admin->isGranted('EDIT')) {
  825. throw new AccessDeniedException();
  826. }
  827. $id = $request->get($this->admin->getIdParameter());
  828. $object = $this->admin->getObject($id);
  829. if (!$object) {
  830. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  831. }
  832. $manager = $this->get('sonata.admin.audit.manager');
  833. if (!$manager->hasReader($this->admin->getClass())) {
  834. throw new NotFoundHttpException(
  835. sprintf(
  836. 'unable to find the audit reader for class : %s',
  837. $this->admin->getClass()
  838. )
  839. );
  840. }
  841. $reader = $manager->getReader($this->admin->getClass());
  842. // retrieve the base revision
  843. $base_object = $reader->find($this->admin->getClass(), $id, $base_revision);
  844. if (!$base_object) {
  845. throw new NotFoundHttpException(
  846. sprintf(
  847. 'unable to find the targeted object `%s` from the revision `%s` with classname : `%s`',
  848. $id,
  849. $base_revision,
  850. $this->admin->getClass()
  851. )
  852. );
  853. }
  854. // retrieve the compare revision
  855. $compare_object = $reader->find($this->admin->getClass(), $id, $compare_revision);
  856. if (!$compare_object) {
  857. throw new NotFoundHttpException(
  858. sprintf(
  859. 'unable to find the targeted object `%s` from the revision `%s` with classname : `%s`',
  860. $id,
  861. $compare_revision,
  862. $this->admin->getClass()
  863. )
  864. );
  865. }
  866. $this->admin->setSubject($base_object);
  867. return $this->render($this->admin->getTemplate('show_compare'), array(
  868. 'action' => 'show',
  869. 'object' => $base_object,
  870. 'object_compare' => $compare_object,
  871. 'elements' => $this->admin->getShow(),
  872. ), null, $request);
  873. }
  874. /**
  875. * Export data to specified format
  876. *
  877. * @param Request $request
  878. *
  879. * @return Response
  880. *
  881. * @throws AccessDeniedException If access is not granted
  882. * @throws \RuntimeException If the export format is invalid
  883. */
  884. public function exportAction(Request $request = null)
  885. {
  886. $request = $this->resolveRequest($request);
  887. if (false === $this->admin->isGranted('EXPORT')) {
  888. throw new AccessDeniedException();
  889. }
  890. $format = $request->get('format');
  891. $allowedExportFormats = (array) $this->admin->getExportFormats();
  892. if (!in_array($format, $allowedExportFormats)) {
  893. throw new \RuntimeException(
  894. sprintf(
  895. 'Export in format `%s` is not allowed for class: `%s`. Allowed formats are: `%s`',
  896. $format,
  897. $this->admin->getClass(),
  898. implode(', ', $allowedExportFormats)
  899. )
  900. );
  901. }
  902. $filename = sprintf(
  903. 'export_%s_%s.%s',
  904. strtolower(substr($this->admin->getClass(), strripos($this->admin->getClass(), '\\') + 1)),
  905. date('Y_m_d_H_i_s', strtotime('now')),
  906. $format
  907. );
  908. return $this->get('sonata.admin.exporter')->getResponse(
  909. $format,
  910. $filename,
  911. $this->admin->getDataSourceIterator()
  912. );
  913. }
  914. /**
  915. * Gets ACL users
  916. *
  917. * @return \Traversable
  918. */
  919. protected function getAclUsers()
  920. {
  921. $aclUsers = array();
  922. $userManagerServiceName = $this->container->getParameter('sonata.admin.security.acl_user_manager');
  923. if ($userManagerServiceName !== null && $this->has($userManagerServiceName)) {
  924. $userManager = $this->get($userManagerServiceName);
  925. if (method_exists($userManager, 'findUsers')) {
  926. $aclUsers = $userManager->findUsers();
  927. }
  928. }
  929. return is_array($aclUsers) ? new \ArrayIterator($aclUsers) : $aclUsers;
  930. }
  931. /**
  932. * Gets ACL roles
  933. *
  934. * @return \Traversable
  935. */
  936. protected function getAclRoles()
  937. {
  938. $aclRoles = array();
  939. $roleHierarchy = $this->container->getParameter('security.role_hierarchy.roles');
  940. $pool = $this->container->get('sonata.admin.pool');
  941. foreach ($pool->getAdminServiceIds() as $id) {
  942. try {
  943. $admin = $pool->getInstance($id);
  944. } catch (\Exception $e) {
  945. continue;
  946. }
  947. $baseRole = $admin->getSecurityHandler()->getBaseRole($admin);
  948. foreach ($admin->getSecurityInformation() as $role => $permissions) {
  949. $role = sprintf($baseRole, $role);
  950. $aclRoles[] = $role;
  951. }
  952. }
  953. foreach ($roleHierarchy as $name => $roles) {
  954. $aclRoles[] = $name;
  955. $aclRoles = array_merge($aclRoles, $roles);
  956. }
  957. $aclRoles = array_unique($aclRoles);
  958. return is_array($aclRoles) ? new \ArrayIterator($aclRoles) : $aclRoles;
  959. }
  960. /**
  961. * Returns the Response object associated to the acl action
  962. *
  963. * @param int|string|null $id
  964. * @param Request $request
  965. *
  966. * @return Response|RedirectResponse
  967. *
  968. * @throws AccessDeniedException If access is not granted.
  969. * @throws NotFoundHttpException If the object does not exist or the ACL is not enabled
  970. */
  971. public function aclAction($id = null, Request $request = null)
  972. {
  973. $request = $this->resolveRequest($request);
  974. if (!$this->admin->isAclEnabled()) {
  975. throw new NotFoundHttpException('ACL are not enabled for this admin');
  976. }
  977. $id = $request->get($this->admin->getIdParameter());
  978. $object = $this->admin->getObject($id);
  979. if (!$object) {
  980. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  981. }
  982. if (false === $this->admin->isGranted('MASTER', $object)) {
  983. throw new AccessDeniedException();
  984. }
  985. $this->admin->setSubject($object);
  986. $aclUsers = $this->getAclUsers();
  987. $aclRoles = $this->getAclRoles();
  988. $adminObjectAclManipulator = $this->get('sonata.admin.object.manipulator.acl.admin');
  989. $adminObjectAclData = new AdminObjectAclData(
  990. $this->admin,
  991. $object,
  992. $aclUsers,
  993. $adminObjectAclManipulator->getMaskBuilderClass(),
  994. $aclRoles
  995. );
  996. $aclUsersForm = $adminObjectAclManipulator->createAclUsersForm($adminObjectAclData);
  997. $aclRolesForm = $adminObjectAclManipulator->createAclRolesForm($adminObjectAclData);
  998. if ($request->getMethod() === 'POST') {
  999. if ($request->request->has(AdminObjectAclManipulator::ACL_USERS_FORM_NAME)) {
  1000. $form = $aclUsersForm;
  1001. $updateMethod = 'updateAclUsers';
  1002. } elseif ($request->request->has(AdminObjectAclManipulator::ACL_ROLES_FORM_NAME)) {
  1003. $form = $aclRolesForm;
  1004. $updateMethod = 'updateAclRoles';
  1005. }
  1006. if (isset($form)) {
  1007. $form->handleRequest($request);
  1008. if ($form->isValid()) {
  1009. $adminObjectAclManipulator->$updateMethod($adminObjectAclData);
  1010. $this->addFlash('sonata_flash_success', 'flash_acl_edit_success');
  1011. return new RedirectResponse($this->admin->generateObjectUrl('acl', $object));
  1012. }
  1013. }
  1014. }
  1015. return $this->render($this->admin->getTemplate('acl'), array(
  1016. 'action' => 'acl',
  1017. 'permissions' => $adminObjectAclData->getUserPermissions(),
  1018. 'object' => $object,
  1019. 'users' => $aclUsers,
  1020. 'roles' => $aclRoles,
  1021. 'aclUsersForm' => $aclUsersForm->createView(),
  1022. 'aclRolesForm' => $aclRolesForm->createView(),
  1023. ), null, $request);
  1024. }
  1025. /**
  1026. * Adds a flash message for type.
  1027. *
  1028. * @param string $type
  1029. * @param string $message
  1030. */
  1031. protected function addFlash($type, $message)
  1032. {
  1033. $this->get('session')
  1034. ->getFlashBag()
  1035. ->add($type, $message);
  1036. }
  1037. /**
  1038. * Validate CSRF token for action without form
  1039. *
  1040. * @param string $intention
  1041. * @param Request $request
  1042. *
  1043. * @throws HttpException
  1044. */
  1045. protected function validateCsrfToken($intention, Request $request = null)
  1046. {
  1047. if (!$this->container->has('form.csrf_provider')) {
  1048. return;
  1049. }
  1050. $request = $this->resolveRequest($request);
  1051. if (!$this->container->get('form.csrf_provider')->isCsrfTokenValid(
  1052. $intention,
  1053. $request->request->get('_sonata_csrf_token', false)
  1054. )) {
  1055. throw new HttpException(400, 'The csrf token is not valid, CSRF attack?');
  1056. }
  1057. }
  1058. /**
  1059. * Escape string for html output
  1060. *
  1061. * @param string $s
  1062. *
  1063. * @return string
  1064. */
  1065. protected function escapeHtml($s)
  1066. {
  1067. return htmlspecialchars($s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
  1068. }
  1069. /**
  1070. * Get CSRF token
  1071. *
  1072. * @param string $intention
  1073. *
  1074. * @return string|false
  1075. */
  1076. protected function getCsrfToken($intention)
  1077. {
  1078. if ($this->container->has('security.csrf.token_manager')) {
  1079. return $this->container->get('security.csrf.token_manager')->getToken($intention)->getValue();
  1080. }
  1081. // TODO: Remove it when bumping requirements to SF 2.4+
  1082. if ($this->container->has('form.csrf_provider')) {
  1083. return $this->container->get('form.csrf_provider')->generateCsrfToken($intention);
  1084. }
  1085. return false;
  1086. }
  1087. /**
  1088. * This method can be overloaded in your custom CRUD controller.
  1089. * It's called from createAction.
  1090. *
  1091. * @param Request $request
  1092. * @param mixed $object
  1093. *
  1094. * @return Response|null
  1095. */
  1096. protected function preCreate(Request $request, $object)
  1097. {
  1098. }
  1099. /**
  1100. * This method can be overloaded in your custom CRUD controller.
  1101. * It's called from editAction.
  1102. *
  1103. * @param Request $request
  1104. * @param mixed $object
  1105. *
  1106. * @return Response|null
  1107. */
  1108. protected function preEdit(Request $request, $object)
  1109. {
  1110. }
  1111. /**
  1112. * This method can be overloaded in your custom CRUD controller.
  1113. * It's called from deleteAction.
  1114. *
  1115. * @param Request $request
  1116. * @param mixed $object
  1117. *
  1118. * @return Response|null
  1119. */
  1120. protected function preDelete(Request $request, $object)
  1121. {
  1122. }
  1123. /**
  1124. * This method can be overloaded in your custom CRUD controller.
  1125. * It's called from showAction.
  1126. *
  1127. * @param Request $request
  1128. * @param mixed $object
  1129. *
  1130. * @return Response|null
  1131. */
  1132. protected function preShow(Request $request, $object)
  1133. {
  1134. }
  1135. /**
  1136. * This method can be overloaded in your custom CRUD controller.
  1137. * It's called from listAction.
  1138. *
  1139. * @param Request $request
  1140. *
  1141. * @return Response|null
  1142. */
  1143. protected function preList(Request $request)
  1144. {
  1145. }
  1146. /**
  1147. * To keep backwards compatibility with older Sonata Admin code.
  1148. *
  1149. * @internal
  1150. */
  1151. private function resolveRequest(Request $request = null)
  1152. {
  1153. if (null === $request) {
  1154. return $this->getRequest();
  1155. }
  1156. return $request;
  1157. }
  1158. }