CRUDController.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820
  1. <?php
  2. /*
  3. * This file is part of the Sonata package.
  4. *
  5. * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Sonata\AdminBundle\Controller;
  11. use Symfony\Component\HttpFoundation\RedirectResponse;
  12. use Symfony\Component\HttpFoundation\Response;
  13. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  14. use Symfony\Component\Security\Core\Exception\AccessDeniedException;
  15. use Symfony\Component\DependencyInjection\ContainerInterface;
  16. use Symfony\Bundle\FrameworkBundle\Controller\Controller;
  17. use Sonata\AdminBundle\Exception\ModelManagerException;
  18. use Symfony\Component\HttpFoundation\Request;
  19. use Sonata\AdminBundle\Datagrid\ProxyQueryInterface;
  20. use Sonata\AdminBundle\Admin\BaseFieldDescription;
  21. use Sonata\AdminBundle\Util\AdminObjectAclData;
  22. class CRUDController extends Controller
  23. {
  24. /**
  25. * The related Admin class
  26. *
  27. * @var \Sonata\AdminBundle\Admin\AdminInterface
  28. */
  29. protected $admin;
  30. /**
  31. * @param mixed $data
  32. * @param integer $status
  33. * @param array $headers
  34. *
  35. * @return Response with json encoded data
  36. */
  37. public function renderJson($data, $status = 200, $headers = array())
  38. {
  39. // fake content-type so browser does not show the download popup when this
  40. // response is rendered through an iframe (used by the jquery.form.js plugin)
  41. // => don't know yet if it is the best solution
  42. if ($this->get('request')->get('_xml_http_request')
  43. && strpos($this->get('request')->headers->get('Content-Type'), 'multipart/form-data') === 0) {
  44. $headers['Content-Type'] = 'text/plain';
  45. } else {
  46. $headers['Content-Type'] = 'application/json';
  47. }
  48. return new Response(json_encode($data), $status, $headers);
  49. }
  50. /**
  51. *
  52. * @return boolean true if the request is done by an ajax like query
  53. */
  54. public function isXmlHttpRequest()
  55. {
  56. return $this->get('request')->isXmlHttpRequest() || $this->get('request')->get('_xml_http_request');
  57. }
  58. /**
  59. * Returns the correct RESTful verb, given either by the request itself or
  60. * via the "_method" parameter.
  61. *
  62. * @return string HTTP method, either
  63. */
  64. protected function getRestMethod()
  65. {
  66. $request = $this->getRequest();
  67. if (Request::getHttpMethodParameterOverride() || !$request->request->has('_method')) {
  68. return $request->getMethod();
  69. }
  70. return $request->request->get('_method');
  71. }
  72. /**
  73. * Sets the Container associated with this Controller.
  74. *
  75. * @param ContainerInterface $container A ContainerInterface instance
  76. */
  77. public function setContainer(ContainerInterface $container = null)
  78. {
  79. $this->container = $container;
  80. $this->configure();
  81. }
  82. /**
  83. * Contextualize the admin class depends on the current request
  84. *
  85. * @throws \RuntimeException
  86. * @return void
  87. */
  88. public function configure()
  89. {
  90. $adminCode = $this->container->get('request')->get('_sonata_admin');
  91. if (!$adminCode) {
  92. throw new \RuntimeException(sprintf('There is no `_sonata_admin` defined for the controller `%s` and the current route `%s`', get_class($this), $this->container->get('request')->get('_route')));
  93. }
  94. $this->admin = $this->container->get('sonata.admin.pool')->getAdminByAdminCode($adminCode);
  95. if (!$this->admin) {
  96. throw new \RuntimeException(sprintf('Unable to find the admin class related to the current controller (%s)', get_class($this)));
  97. }
  98. $rootAdmin = $this->admin;
  99. if ($this->admin->isChild()) {
  100. $this->admin->setCurrentChild(true);
  101. $rootAdmin = $rootAdmin->getParent();
  102. }
  103. $request = $this->container->get('request');
  104. $rootAdmin->setRequest($request);
  105. if ($request->get('uniqid')) {
  106. $this->admin->setUniqid($request->get('uniqid'));
  107. }
  108. }
  109. /**
  110. * return the base template name
  111. *
  112. * @return string the template name
  113. */
  114. public function getBaseTemplate()
  115. {
  116. if ($this->isXmlHttpRequest()) {
  117. return $this->admin->getTemplate('ajax');
  118. }
  119. return $this->admin->getTemplate('layout');
  120. }
  121. /**
  122. * @param string $view
  123. * @param array $parameters
  124. * @param Response $response
  125. *
  126. * @return Response
  127. */
  128. public function render($view, array $parameters = array(), Response $response = null)
  129. {
  130. $parameters['admin'] = isset($parameters['admin']) ? $parameters['admin'] : $this->admin;
  131. $parameters['base_template'] = isset($parameters['base_template']) ? $parameters['base_template'] : $this->getBaseTemplate();
  132. $parameters['admin_pool'] = $this->get('sonata.admin.pool');
  133. return parent::render($view, $parameters, $response);
  134. }
  135. /**
  136. * return the Response object associated to the list action
  137. *
  138. * @throws \Symfony\Component\Security\Core\Exception\AccessDeniedException
  139. *
  140. * @return Response
  141. */
  142. public function listAction()
  143. {
  144. if (false === $this->admin->isGranted('LIST')) {
  145. throw new AccessDeniedException();
  146. }
  147. $datagrid = $this->admin->getDatagrid();
  148. $formView = $datagrid->getForm()->createView();
  149. // set the theme for the current Admin Form
  150. $this->get('twig')->getExtension('form')->renderer->setTheme($formView, $this->admin->getFilterTheme());
  151. return $this->render($this->admin->getTemplate('list'), array(
  152. 'action' => 'list',
  153. 'form' => $formView,
  154. 'datagrid' => $datagrid
  155. ));
  156. }
  157. /**
  158. * execute a batch delete
  159. *
  160. * @throws \Symfony\Component\Security\Core\Exception\AccessDeniedException
  161. *
  162. * @param \Sonata\AdminBundle\Datagrid\ProxyQueryInterface $query
  163. *
  164. * @return \Symfony\Component\HttpFoundation\RedirectResponse
  165. */
  166. public function batchActionDelete(ProxyQueryInterface $query)
  167. {
  168. if (false === $this->admin->isGranted('DELETE')) {
  169. throw new AccessDeniedException();
  170. }
  171. $modelManager = $this->admin->getModelManager();
  172. try {
  173. $modelManager->batchDelete($this->admin->getClass(), $query);
  174. $this->addFlash('sonata_flash_success', 'flash_batch_delete_success');
  175. } catch ( ModelManagerException $e ) {
  176. $this->addFlash('sonata_flash_error', 'flash_batch_delete_error');
  177. }
  178. return new RedirectResponse($this->admin->generateUrl('list', array('filter' => $this->admin->getFilterParameters())));
  179. }
  180. /**
  181. * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException|\Symfony\Component\Security\Core\Exception\AccessDeniedException
  182. *
  183. * @param mixed $id
  184. *
  185. * @return Response|RedirectResponse
  186. */
  187. public function deleteAction($id)
  188. {
  189. $id = $this->get('request')->get($this->admin->getIdParameter());
  190. $object = $this->admin->getObject($id);
  191. if (!$object) {
  192. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  193. }
  194. if (false === $this->admin->isGranted('DELETE', $object)) {
  195. throw new AccessDeniedException();
  196. }
  197. if ($this->getRestMethod() == 'DELETE') {
  198. try {
  199. $this->admin->delete($object);
  200. if ($this->isXmlHttpRequest()) {
  201. return $this->renderJson(array('result' => 'ok'));
  202. }
  203. $this->addFlash('sonata_flash_success', 'flash_delete_success');
  204. } catch (ModelManagerException $e) {
  205. if ($this->isXmlHttpRequest()) {
  206. return $this->renderJson(array('result' => 'error'));
  207. }
  208. $this->addFlash('sonata_flash_error', 'flash_delete_error');
  209. }
  210. return new RedirectResponse($this->admin->generateUrl('list'));
  211. }
  212. return $this->render($this->admin->getTemplate('delete'), array(
  213. 'object' => $object,
  214. 'action' => 'delete'
  215. ));
  216. }
  217. /**
  218. * return the Response object associated to the edit action
  219. *
  220. *
  221. * @param mixed $id
  222. *
  223. * @throws \Symfony\Component\Security\Core\Exception\AccessDeniedException
  224. * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
  225. *
  226. * @return Response
  227. */
  228. public function editAction($id = null)
  229. {
  230. // the key used to lookup the template
  231. $templateKey = 'edit';
  232. $id = $this->get('request')->get($this->admin->getIdParameter());
  233. $object = $this->admin->getObject($id);
  234. if (!$object) {
  235. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  236. }
  237. if (false === $this->admin->isGranted('EDIT', $object)) {
  238. throw new AccessDeniedException();
  239. }
  240. $this->admin->setSubject($object);
  241. /** @var $form \Symfony\Component\Form\Form */
  242. $form = $this->admin->getForm();
  243. $form->setData($object);
  244. if ($this->getRestMethod() == 'POST') {
  245. $form->bind($this->get('request'));
  246. $isFormValid = $form->isValid();
  247. // persist if the form was valid and if in preview mode the preview was approved
  248. if ($isFormValid && (!$this->isInPreviewMode() || $this->isPreviewApproved())) {
  249. $this->admin->update($object);
  250. $this->addFlash('sonata_flash_success', 'flash_edit_success');
  251. if ($this->isXmlHttpRequest()) {
  252. return $this->renderJson(array(
  253. 'result' => 'ok',
  254. 'objectId' => $this->admin->getNormalizedIdentifier($object)
  255. ));
  256. }
  257. // redirect to edit mode
  258. return $this->redirectTo($object);
  259. }
  260. // show an error message if the form failed validation
  261. if (!$isFormValid) {
  262. if (!$this->isXmlHttpRequest()) {
  263. $this->addFlash('sonata_flash_error', 'flash_edit_error');
  264. }
  265. } elseif ($this->isPreviewRequested()) {
  266. // enable the preview template if the form was valid and preview was requested
  267. $templateKey = 'preview';
  268. $this->admin->getShow();
  269. }
  270. }
  271. $view = $form->createView();
  272. // set the theme for the current Admin Form
  273. $this->get('twig')->getExtension('form')->renderer->setTheme($view, $this->admin->getFormTheme());
  274. return $this->render($this->admin->getTemplate($templateKey), array(
  275. 'action' => 'edit',
  276. 'form' => $view,
  277. 'object' => $object,
  278. ));
  279. }
  280. /**
  281. * redirect the user depend on this choice
  282. *
  283. * @param object $object
  284. *
  285. * @return Response
  286. */
  287. public function redirectTo($object)
  288. {
  289. $url = false;
  290. if ($this->get('request')->get('btn_update_and_list')) {
  291. $url = $this->admin->generateUrl('list');
  292. }
  293. if ($this->get('request')->get('btn_create_and_list')) {
  294. $url = $this->admin->generateUrl('list');
  295. }
  296. if ($this->get('request')->get('btn_create_and_create')) {
  297. $params = array();
  298. if ($this->admin->hasActiveSubClass()) {
  299. $params['subclass'] = $this->get('request')->get('subclass');
  300. }
  301. $url = $this->admin->generateUrl('create', $params);
  302. }
  303. if (!$url) {
  304. $url = $this->admin->generateObjectUrl('edit', $object);
  305. }
  306. return new RedirectResponse($url);
  307. }
  308. /**
  309. * return the Response object associated to the batch action
  310. *
  311. * @throws \RuntimeException
  312. * @return Response
  313. */
  314. public function batchAction()
  315. {
  316. if ($this->getRestMethod() != 'POST') {
  317. throw new \RuntimeException('invalid request type, POST expected');
  318. }
  319. $confirmation = $this->get('request')->get('confirmation', false);
  320. if ($data = json_decode($this->get('request')->get('data'), true)) {
  321. $action = $data['action'];
  322. $idx = $data['idx'];
  323. $all_elements = $data['all_elements'];
  324. $this->get('request')->request->replace($data);
  325. } else {
  326. $this->get('request')->request->set('idx', $this->get('request')->get('idx', array()));
  327. $this->get('request')->request->set('all_elements', $this->get('request')->get('all_elements', false));
  328. $action = $this->get('request')->get('action');
  329. $idx = $this->get('request')->get('idx');
  330. $all_elements = $this->get('request')->get('all_elements');
  331. $data = $this->get('request')->request->all();
  332. }
  333. $batchActions = $this->admin->getBatchActions();
  334. if (!array_key_exists($action, $batchActions)) {
  335. throw new \RuntimeException(sprintf('The `%s` batch action is not defined', $action));
  336. }
  337. $camelizedAction = BaseFieldDescription::camelize($action);
  338. $isRelevantAction = sprintf('batchAction%sIsRelevant', ucfirst($camelizedAction));
  339. if (method_exists($this, $isRelevantAction)) {
  340. $nonRelevantMessage = call_user_func(array($this, $isRelevantAction), $idx, $all_elements);
  341. } else {
  342. $nonRelevantMessage = count($idx) != 0 || $all_elements; // at least one item is selected
  343. }
  344. if (!$nonRelevantMessage) { // default non relevant message (if false of null)
  345. $nonRelevantMessage = 'flash_batch_empty';
  346. }
  347. $datagrid = $this->admin->getDatagrid();
  348. $datagrid->buildPager();
  349. if (true !== $nonRelevantMessage) {
  350. $this->addFlash('sonata_flash_info', $nonRelevantMessage);
  351. return new RedirectResponse($this->admin->generateUrl('list', array('filter' => $this->admin->getFilterParameters())));
  352. }
  353. $askConfirmation = isset($batchActions[$action]['ask_confirmation']) ? $batchActions[$action]['ask_confirmation'] : true;
  354. if ($askConfirmation && $confirmation != 'ok') {
  355. $formView = $datagrid->getForm()->createView();
  356. return $this->render($this->admin->getTemplate('batch_confirmation'), array(
  357. 'action' => 'list',
  358. 'datagrid' => $datagrid,
  359. 'form' => $formView,
  360. 'data' => $data,
  361. ));
  362. }
  363. // execute the action, batchActionXxxxx
  364. $final_action = sprintf('batchAction%s', ucfirst($camelizedAction));
  365. if (!method_exists($this, $final_action)) {
  366. throw new \RuntimeException(sprintf('A `%s::%s` method must be created', get_class($this), $final_action));
  367. }
  368. $query = $datagrid->getQuery();
  369. $query->setFirstResult(null);
  370. $query->setMaxResults(null);
  371. if (count($idx) > 0) {
  372. $this->admin->getModelManager()->addIdentifiersToQuery($this->admin->getClass(), $query, $idx);
  373. } elseif (!$all_elements) {
  374. $query = null;
  375. }
  376. return call_user_func(array($this, $final_action), $query);
  377. }
  378. /**
  379. * return the Response object associated to the create action
  380. *
  381. * @throws \Symfony\Component\Security\Core\Exception\AccessDeniedException
  382. * @return Response
  383. */
  384. public function createAction()
  385. {
  386. // the key used to lookup the template
  387. $templateKey = 'edit';
  388. if (false === $this->admin->isGranted('CREATE')) {
  389. throw new AccessDeniedException();
  390. }
  391. $object = $this->admin->getNewInstance();
  392. $this->admin->setSubject($object);
  393. /** @var $form \Symfony\Component\Form\Form */
  394. $form = $this->admin->getForm();
  395. $form->setData($object);
  396. if ($this->getRestMethod()== 'POST') {
  397. $form->bind($this->get('request'));
  398. $isFormValid = $form->isValid();
  399. // persist if the form was valid and if in preview mode the preview was approved
  400. if ($isFormValid && (!$this->isInPreviewMode() || $this->isPreviewApproved())) {
  401. $this->admin->create($object);
  402. if ($this->isXmlHttpRequest()) {
  403. return $this->renderJson(array(
  404. 'result' => 'ok',
  405. 'objectId' => $this->admin->getNormalizedIdentifier($object)
  406. ));
  407. }
  408. $this->addFlash('sonata_flash_success','flash_create_success');
  409. // redirect to edit mode
  410. return $this->redirectTo($object);
  411. }
  412. // show an error message if the form failed validation
  413. if (!$isFormValid) {
  414. if (!$this->isXmlHttpRequest()) {
  415. $this->addFlash('sonata_flash_error', 'flash_create_error');
  416. }
  417. } elseif ($this->isPreviewRequested()) {
  418. // pick the preview template if the form was valid and preview was requested
  419. $templateKey = 'preview';
  420. $this->admin->getShow();
  421. }
  422. }
  423. $view = $form->createView();
  424. // set the theme for the current Admin Form
  425. $this->get('twig')->getExtension('form')->renderer->setTheme($view, $this->admin->getFormTheme());
  426. return $this->render($this->admin->getTemplate($templateKey), array(
  427. 'action' => 'create',
  428. 'form' => $view,
  429. 'object' => $object,
  430. ));
  431. }
  432. /**
  433. * Returns true if the preview is requested to be shown
  434. *
  435. * @return boolean
  436. */
  437. protected function isPreviewRequested()
  438. {
  439. return ($this->get('request')->get('btn_preview') !== null);
  440. }
  441. /**
  442. * Returns true if the preview has been approved
  443. *
  444. * @return boolean
  445. */
  446. protected function isPreviewApproved()
  447. {
  448. return ($this->get('request')->get('btn_preview_approve') !== null);
  449. }
  450. /**
  451. * Returns true if the request is in the preview workflow
  452. *
  453. * That means either a preview is requested or the preview has already been shown
  454. * and it got approved/declined.
  455. *
  456. * @return boolean
  457. */
  458. protected function isInPreviewMode()
  459. {
  460. return $this->admin->supportsPreviewMode()
  461. && ($this->isPreviewRequested()
  462. || $this->isPreviewApproved()
  463. || $this->isPreviewDeclined());
  464. }
  465. /**
  466. * Returns true if the preview has been declined
  467. *
  468. * @return boolean
  469. */
  470. protected function isPreviewDeclined()
  471. {
  472. return ($this->get('request')->get('btn_preview_decline') !== null);
  473. }
  474. /**
  475. * return the Response object associated to the view action
  476. *
  477. * @param null $id
  478. *
  479. * @throws \Symfony\Component\Security\Core\Exception\AccessDeniedException
  480. * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
  481. *
  482. * @return Response
  483. */
  484. public function showAction($id = null)
  485. {
  486. $id = $this->get('request')->get($this->admin->getIdParameter());
  487. $object = $this->admin->getObject($id);
  488. if (!$object) {
  489. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  490. }
  491. if (false === $this->admin->isGranted('VIEW', $object)) {
  492. throw new AccessDeniedException();
  493. }
  494. $this->admin->setSubject($object);
  495. return $this->render($this->admin->getTemplate('show'), array(
  496. 'action' => 'show',
  497. 'object' => $object,
  498. 'elements' => $this->admin->getShow(),
  499. ));
  500. }
  501. /**
  502. * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException|\Symfony\Component\Security\Core\Exception\AccessDeniedException
  503. *
  504. * @param mixed $id
  505. *
  506. * @return Response
  507. */
  508. public function historyAction($id = null)
  509. {
  510. if (false === $this->admin->isGranted('EDIT')) {
  511. throw new AccessDeniedException();
  512. }
  513. $id = $this->get('request')->get($this->admin->getIdParameter());
  514. $object = $this->admin->getObject($id);
  515. if (!$object) {
  516. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  517. }
  518. $manager = $this->get('sonata.admin.audit.manager');
  519. if (!$manager->hasReader($this->admin->getClass())) {
  520. throw new NotFoundHttpException(sprintf('unable to find the audit reader for class : %s', $this->admin->getClass()));
  521. }
  522. $reader = $manager->getReader($this->admin->getClass());
  523. $revisions = $reader->findRevisions($this->admin->getClass(), $id);
  524. return $this->render($this->admin->getTemplate('history'), array(
  525. 'action' => 'history',
  526. 'object' => $object,
  527. 'revisions' => $revisions,
  528. ));
  529. }
  530. /**
  531. * @param null $id
  532. * @param string $revision
  533. *
  534. * @throws \Symfony\Component\Security\Core\Exception\AccessDeniedException
  535. * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
  536. *
  537. * @return Response
  538. */
  539. public function historyViewRevisionAction($id = null, $revision = null)
  540. {
  541. if (false === $this->admin->isGranted('EDIT')) {
  542. throw new AccessDeniedException();
  543. }
  544. $id = $this->get('request')->get($this->admin->getIdParameter());
  545. $object = $this->admin->getObject($id);
  546. if (!$object) {
  547. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  548. }
  549. $manager = $this->get('sonata.admin.audit.manager');
  550. if (!$manager->hasReader($this->admin->getClass())) {
  551. throw new NotFoundHttpException(sprintf('unable to find the audit reader for class : %s', $this->admin->getClass()));
  552. }
  553. $reader = $manager->getReader($this->admin->getClass());
  554. // retrieve the revisioned object
  555. $object = $reader->find($this->admin->getClass(), $id, $revision);
  556. if (!$object) {
  557. throw new NotFoundHttpException(sprintf('unable to find the targeted object `%s` from the revision `%s` with classname : `%s`', $id, $revision, $this->admin->getClass()));
  558. }
  559. $this->admin->setSubject($object);
  560. return $this->render($this->admin->getTemplate('show'), array(
  561. 'action' => 'show',
  562. 'object' => $object,
  563. 'elements' => $this->admin->getShow(),
  564. ));
  565. }
  566. /**
  567. * @param Request $request
  568. *
  569. * @throws \RuntimeException
  570. * @throws \Symfony\Component\Security\Core\Exception\AccessDeniedException
  571. *
  572. * @return Response
  573. */
  574. public function exportAction(Request $request)
  575. {
  576. if (false === $this->admin->isGranted('EXPORT')) {
  577. throw new AccessDeniedException();
  578. }
  579. $format = $request->get('format');
  580. $allowedExportFormats = (array) $this->admin->getExportFormats();
  581. if (!in_array($format, $allowedExportFormats) ) {
  582. throw new \RuntimeException(sprintf('Export in format `%s` is not allowed for class: `%s`. Allowed formats are: `%s`', $format, $this->admin->getClass(), implode(', ', $allowedExportFormats)));
  583. }
  584. $filename = sprintf('export_%s_%s.%s',
  585. strtolower(substr($this->admin->getClass(), strripos($this->admin->getClass(), '\\') + 1)),
  586. date('Y_m_d_H_i_s', strtotime('now')),
  587. $format
  588. );
  589. return $this->get('sonata.admin.exporter')->getResponse($format, $filename, $this->admin->getDataSourceIterator());
  590. }
  591. /**
  592. * Gets ACL users
  593. *
  594. * @return \Traversable
  595. */
  596. protected function getAclUsers()
  597. {
  598. $aclUsers = array();
  599. $userManagerServiceName = $this->container->getParameter('sonata.admin.security.acl_user_manager');
  600. if ($userManagerServiceName !== null && $this->has($userManagerServiceName)) {
  601. $userManager = $this->get($userManagerServiceName);
  602. if (method_exists($userManager, 'findUsers')) {
  603. $aclUsers = $userManager->findUsers();
  604. }
  605. }
  606. return is_array($aclUsers) ? new \ArrayIterator($aclUsers) : $aclUsers;
  607. }
  608. /**
  609. * return the Response object associated to the acl action
  610. *
  611. * @param null $id
  612. *
  613. * @throws \Symfony\Component\Security\Core\Exception\AccessDeniedException
  614. * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
  615. *
  616. * @return Response
  617. */
  618. public function aclAction($id = null)
  619. {
  620. if (!$this->admin->isAclEnabled()) {
  621. throw new NotFoundHttpException('ACL are not enabled for this admin');
  622. }
  623. $id = $this->get('request')->get($this->admin->getIdParameter());
  624. $object = $this->admin->getObject($id);
  625. if (!$object) {
  626. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  627. }
  628. if (false === $this->admin->isGranted('MASTER', $object)) {
  629. throw new AccessDeniedException();
  630. }
  631. $this->admin->setSubject($object);
  632. $aclUsers = $this->getAclUsers();
  633. $adminObjectAclManipulator = $this->get('sonata.admin.object.manipulator.acl.admin');
  634. $adminObjectAclData = new AdminObjectAclData(
  635. $this->admin,
  636. $object,
  637. $aclUsers,
  638. $adminObjectAclManipulator->getMaskBuilderClass()
  639. );
  640. $form = $adminObjectAclManipulator->createForm($adminObjectAclData);
  641. $request = $this->getRequest();
  642. if ($request->getMethod() === 'POST') {
  643. $form->bind($request);
  644. if ($form->isValid()) {
  645. $adminObjectAclManipulator->updateAcl($adminObjectAclData);
  646. $this->addFlash('sonata_flash_success', 'flash_acl_edit_success');
  647. return new RedirectResponse($this->admin->generateObjectUrl('acl', $object));
  648. }
  649. }
  650. return $this->render($this->admin->getTemplate('acl'), array(
  651. 'action' => 'acl',
  652. 'permissions' => $adminObjectAclData->getUserPermissions(),
  653. 'object' => $object,
  654. 'users' => $aclUsers,
  655. 'form' => $form->createView()
  656. ));
  657. }
  658. /**
  659. * Adds a flash message for type.
  660. *
  661. * @param string $type
  662. * @param string $message
  663. */
  664. public function addFlash($type, $message)
  665. {
  666. $this->get('session')
  667. ->getFlashBag()
  668. ->add($type, $message);
  669. }
  670. }