CRUDController.php 45 KB

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