CRUDController.php 43 KB

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