CRUDController.php 45 KB

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