CRUDController.php 43 KB

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