CRUDController.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979
  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\HttpException;
  14. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  15. use Symfony\Component\Security\Core\Exception\AccessDeniedException;
  16. use Symfony\Component\DependencyInjection\ContainerInterface;
  17. use Symfony\Bundle\FrameworkBundle\Controller\Controller;
  18. use Sonata\AdminBundle\Exception\ModelManagerException;
  19. use Symfony\Component\HttpFoundation\Request;
  20. use Sonata\AdminBundle\Datagrid\ProxyQueryInterface;
  21. use Sonata\AdminBundle\Admin\BaseFieldDescription;
  22. use Sonata\AdminBundle\Util\AdminObjectAclData;
  23. use Sonata\AdminBundle\Admin\AdminInterface;
  24. class CRUDController extends Controller
  25. {
  26. /**
  27. * The related Admin class
  28. *
  29. * @var AdminInterface
  30. */
  31. protected $admin;
  32. /**
  33. * Render JSON
  34. *
  35. * @param mixed $data
  36. * @param integer $status
  37. * @param array $headers
  38. *
  39. * @return Response with json encoded data
  40. */
  41. protected function renderJson($data, $status = 200, $headers = array())
  42. {
  43. // fake content-type so browser does not show the download popup when this
  44. // response is rendered through an iframe (used by the jquery.form.js plugin)
  45. // => don't know yet if it is the best solution
  46. if ($this->get('request')->get('_xml_http_request')
  47. && strpos($this->get('request')->headers->get('Content-Type'), 'multipart/form-data') === 0) {
  48. $headers['Content-Type'] = 'text/plain';
  49. } else {
  50. $headers['Content-Type'] = 'application/json';
  51. }
  52. return new Response(json_encode($data), $status, $headers);
  53. }
  54. /**
  55. * Returns true if the request is a XMLHttpRequest.
  56. *
  57. * @return bool True if the request is an XMLHttpRequest, false otherwise
  58. */
  59. protected function isXmlHttpRequest()
  60. {
  61. return $this->get('request')->isXmlHttpRequest() || $this->get('request')->get('_xml_http_request');
  62. }
  63. /**
  64. * Returns the correct RESTful verb, given either by the request itself or
  65. * via the "_method" parameter.
  66. *
  67. * @return string HTTP method, either
  68. */
  69. protected function getRestMethod()
  70. {
  71. $request = $this->getRequest();
  72. if (Request::getHttpMethodParameterOverride() || !$request->request->has('_method')) {
  73. return $request->getMethod();
  74. }
  75. return $request->request->get('_method');
  76. }
  77. /**
  78. * Sets the Container associated with this Controller.
  79. *
  80. * @param ContainerInterface $container A ContainerInterface instance
  81. */
  82. public function setContainer(ContainerInterface $container = null)
  83. {
  84. $this->container = $container;
  85. $this->configure();
  86. }
  87. /**
  88. * Contextualize the admin class depends on the current request
  89. *
  90. * @throws \RuntimeException
  91. */
  92. protected function configure()
  93. {
  94. $adminCode = $this->container->get('request')->get('_sonata_admin');
  95. if (!$adminCode) {
  96. 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')));
  97. }
  98. $this->admin = $this->container->get('sonata.admin.pool')->getAdminByAdminCode($adminCode);
  99. if (!$this->admin) {
  100. throw new \RuntimeException(sprintf('Unable to find the admin class related to the current controller (%s)', get_class($this)));
  101. }
  102. $rootAdmin = $this->admin;
  103. if ($this->admin->isChild()) {
  104. $this->admin->setCurrentChild(true);
  105. $rootAdmin = $rootAdmin->getParent();
  106. }
  107. $request = $this->container->get('request');
  108. $rootAdmin->setRequest($request);
  109. if ($request->get('uniqid')) {
  110. $this->admin->setUniqid($request->get('uniqid'));
  111. }
  112. }
  113. /**
  114. * Returns the base template name
  115. *
  116. * @return string The template name
  117. */
  118. protected function getBaseTemplate()
  119. {
  120. if ($this->isXmlHttpRequest()) {
  121. return $this->admin->getTemplate('ajax');
  122. }
  123. return $this->admin->getTemplate('layout');
  124. }
  125. /**
  126. * {@inheritdoc}
  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. * List action
  137. *
  138. * @return Response
  139. *
  140. * @throws AccessDeniedException If access is not granted
  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. 'csrf_token' => $this->getCsrfToken('sonata.batch'),
  156. ));
  157. }
  158. /**
  159. * Execute a batch delete
  160. *
  161. * @param ProxyQueryInterface $query
  162. *
  163. * @return RedirectResponse
  164. *
  165. * @throws AccessDeniedException If access is not granted
  166. */
  167. public function batchActionDelete(ProxyQueryInterface $query)
  168. {
  169. if (false === $this->admin->isGranted('DELETE')) {
  170. throw new AccessDeniedException();
  171. }
  172. $modelManager = $this->admin->getModelManager();
  173. try {
  174. $modelManager->batchDelete($this->admin->getClass(), $query);
  175. $this->addFlash('sonata_flash_success', 'flash_batch_delete_success');
  176. } catch (ModelManagerException $e) {
  177. $this->addFlash('sonata_flash_error', 'flash_batch_delete_error');
  178. }
  179. return new RedirectResponse($this->admin->generateUrl('list', array('filter' => $this->admin->getFilterParameters())));
  180. }
  181. /**
  182. * Delete action
  183. *
  184. * @param int|string|null $id
  185. *
  186. * @return Response|RedirectResponse
  187. *
  188. * @throws NotFoundHttpException If the object does not exist
  189. * @throws AccessDeniedException If access is not granted
  190. */
  191. public function deleteAction($id)
  192. {
  193. $id = $this->get('request')->get($this->admin->getIdParameter());
  194. $object = $this->admin->getObject($id);
  195. if (!$object) {
  196. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  197. }
  198. if (false === $this->admin->isGranted('DELETE', $object)) {
  199. throw new AccessDeniedException();
  200. }
  201. if ($this->getRestMethod() == 'DELETE') {
  202. // check the csrf token
  203. $this->validateCsrfToken('sonata.delete');
  204. try {
  205. $this->admin->delete($object);
  206. if ($this->isXmlHttpRequest()) {
  207. return $this->renderJson(array('result' => 'ok'));
  208. }
  209. $this->addFlash(
  210. 'sonata_flash_success',
  211. $this->admin->trans(
  212. 'flash_delete_success',
  213. array('%name%' => $this->admin->toString($object)),
  214. 'SonataAdminBundle'
  215. )
  216. );
  217. } catch (ModelManagerException $e) {
  218. if ($this->isXmlHttpRequest()) {
  219. return $this->renderJson(array('result' => 'error'));
  220. }
  221. $this->addFlash(
  222. 'sonata_flash_error',
  223. $this->admin->trans(
  224. 'flash_delete_error',
  225. array('%name%' => $this->admin->toString($object)),
  226. 'SonataAdminBundle'
  227. )
  228. );
  229. }
  230. return $this->redirectTo($object);
  231. }
  232. return $this->render($this->admin->getTemplate('delete'), array(
  233. 'object' => $object,
  234. 'action' => 'delete',
  235. 'csrf_token' => $this->getCsrfToken('sonata.delete')
  236. ));
  237. }
  238. /**
  239. * Edit action
  240. *
  241. * @param int|string|null $id
  242. *
  243. * @return Response|RedirectResponse
  244. *
  245. * @throws NotFoundHttpException If the object does not exist
  246. * @throws AccessDeniedException If access is not granted
  247. */
  248. public function editAction($id = null)
  249. {
  250. // the key used to lookup the template
  251. $templateKey = 'edit';
  252. $id = $this->get('request')->get($this->admin->getIdParameter());
  253. $object = $this->admin->getObject($id);
  254. if (!$object) {
  255. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  256. }
  257. if (false === $this->admin->isGranted('EDIT', $object)) {
  258. throw new AccessDeniedException();
  259. }
  260. $this->admin->setSubject($object);
  261. /** @var $form \Symfony\Component\Form\Form */
  262. $form = $this->admin->getForm();
  263. $form->setData($object);
  264. if ($this->getRestMethod() == 'POST') {
  265. $form->submit($this->get('request'));
  266. $isFormValid = $form->isValid();
  267. // persist if the form was valid and if in preview mode the preview was approved
  268. if ($isFormValid && (!$this->isInPreviewMode() || $this->isPreviewApproved())) {
  269. try {
  270. $object = $this->admin->update($object);
  271. if ($this->isXmlHttpRequest()) {
  272. return $this->renderJson(array(
  273. 'result' => 'ok',
  274. 'objectId' => $this->admin->getNormalizedIdentifier($object)
  275. ));
  276. }
  277. $this->addFlash('sonata_flash_success', $this->admin->trans('flash_edit_success', array('%name%' => $this->admin->toString($object)), 'SonataAdminBundle'));
  278. // redirect to edit mode
  279. return $this->redirectTo($object);
  280. } catch (ModelManagerException $e) {
  281. $isFormValid = false;
  282. }
  283. }
  284. // show an error message if the form failed validation
  285. if (!$isFormValid) {
  286. if (!$this->isXmlHttpRequest()) {
  287. $this->addFlash('sonata_flash_error', $this->admin->trans('flash_edit_error', array('%name%' => $this->admin->toString($object)), 'SonataAdminBundle'));
  288. }
  289. } elseif ($this->isPreviewRequested()) {
  290. // enable the preview template if the form was valid and preview was requested
  291. $templateKey = 'preview';
  292. $this->admin->getShow();
  293. }
  294. }
  295. $view = $form->createView();
  296. // set the theme for the current Admin Form
  297. $this->get('twig')->getExtension('form')->renderer->setTheme($view, $this->admin->getFormTheme());
  298. return $this->render($this->admin->getTemplate($templateKey), array(
  299. 'action' => 'edit',
  300. 'form' => $view,
  301. 'object' => $object,
  302. ));
  303. }
  304. /**
  305. * Redirect the user depend on this choice
  306. *
  307. * @param object $object
  308. *
  309. * @return RedirectResponse
  310. */
  311. protected function redirectTo($object)
  312. {
  313. $url = false;
  314. if (null !== $this->get('request')->get('btn_update_and_list')) {
  315. $url = $this->admin->generateUrl('list');
  316. }
  317. if (null !== $this->get('request')->get('btn_create_and_list')) {
  318. $url = $this->admin->generateUrl('list');
  319. }
  320. if (null !== $this->get('request')->get('btn_create_and_create')) {
  321. $params = array();
  322. if ($this->admin->hasActiveSubClass()) {
  323. $params['subclass'] = $this->get('request')->get('subclass');
  324. }
  325. $url = $this->admin->generateUrl('create', $params);
  326. }
  327. if ($this->getRestMethod() == 'DELETE') {
  328. $url = $this->admin->generateUrl('list');
  329. }
  330. if (!$url) {
  331. $url = $this->admin->generateObjectUrl('edit', $object);
  332. }
  333. return new RedirectResponse($url);
  334. }
  335. /**
  336. * Batch action
  337. *
  338. * @return Response|RedirectResponse
  339. *
  340. * @throws NotFoundHttpException If the HTTP method is not POST
  341. * @throws \RuntimeException If the batch action is not defined
  342. */
  343. public function batchAction()
  344. {
  345. $restMethod = $this->getRestMethod();
  346. if ('POST' !== $restMethod) {
  347. throw $this->createNotFoundException(sprintf('Invalid request type "%s", POST expected', $restMethod));
  348. }
  349. // check the csrf token
  350. $this->validateCsrfToken('sonata.batch');
  351. $confirmation = $this->get('request')->get('confirmation', false);
  352. if ($data = json_decode($this->get('request')->get('data'), true)) {
  353. $action = $data['action'];
  354. $idx = $data['idx'];
  355. $allElements = $data['all_elements'];
  356. $this->get('request')->request->replace($data);
  357. } else {
  358. $this->get('request')->request->set('idx', $this->get('request')->get('idx', array()));
  359. $this->get('request')->request->set('all_elements', $this->get('request')->get('all_elements', false));
  360. $action = $this->get('request')->get('action');
  361. $idx = $this->get('request')->get('idx');
  362. $allElements = $this->get('request')->get('all_elements');
  363. $data = $this->get('request')->request->all();
  364. unset($data['_sonata_csrf_token']);
  365. }
  366. $batchActions = $this->admin->getBatchActions();
  367. if (!array_key_exists($action, $batchActions)) {
  368. throw new \RuntimeException(sprintf('The `%s` batch action is not defined', $action));
  369. }
  370. $camelizedAction = BaseFieldDescription::camelize($action);
  371. $isRelevantAction = sprintf('batchAction%sIsRelevant', ucfirst($camelizedAction));
  372. if (method_exists($this, $isRelevantAction)) {
  373. $nonRelevantMessage = call_user_func(array($this, $isRelevantAction), $idx, $allElements);
  374. } else {
  375. $nonRelevantMessage = count($idx) != 0 || $allElements; // at least one item is selected
  376. }
  377. if (!$nonRelevantMessage) { // default non relevant message (if false of null)
  378. $nonRelevantMessage = 'flash_batch_empty';
  379. }
  380. $datagrid = $this->admin->getDatagrid();
  381. $datagrid->buildPager();
  382. if (true !== $nonRelevantMessage) {
  383. $this->addFlash('sonata_flash_info', $nonRelevantMessage);
  384. return new RedirectResponse($this->admin->generateUrl('list', array('filter' => $this->admin->getFilterParameters())));
  385. }
  386. $askConfirmation = isset($batchActions[$action]['ask_confirmation']) ? $batchActions[$action]['ask_confirmation'] : true;
  387. if ($askConfirmation && $confirmation != 'ok') {
  388. $actionLabel = $this->admin->trans($this->admin->getTranslationLabel($action, 'action'));
  389. $formView = $datagrid->getForm()->createView();
  390. return $this->render($this->admin->getTemplate('batch_confirmation'), array(
  391. 'action' => 'list',
  392. 'action_label' => $actionLabel,
  393. 'datagrid' => $datagrid,
  394. 'form' => $formView,
  395. 'data' => $data,
  396. 'csrf_token' => $this->getCsrfToken('sonata.batch'),
  397. ));
  398. }
  399. // execute the action, batchActionXxxxx
  400. $finalAction = sprintf('batchAction%s', ucfirst($camelizedAction));
  401. if (!method_exists($this, $finalAction)) {
  402. throw new \RuntimeException(sprintf('A `%s::%s` method must be created', get_class($this), $finalAction));
  403. }
  404. $query = $datagrid->getQuery();
  405. $query->setFirstResult(null);
  406. $query->setMaxResults(null);
  407. $this->admin->preBatchAction($action, $query, $idx, $allElements);
  408. if (count($idx) > 0) {
  409. $this->admin->getModelManager()->addIdentifiersToQuery($this->admin->getClass(), $query, $idx);
  410. } elseif (!$allElements) {
  411. $query = null;
  412. }
  413. return call_user_func(array($this, $finalAction), $query);
  414. }
  415. /**
  416. * Create action
  417. *
  418. * @return Response
  419. *
  420. * @throws AccessDeniedException If access is not granted
  421. */
  422. public function createAction()
  423. {
  424. // the key used to lookup the template
  425. $templateKey = 'edit';
  426. if (false === $this->admin->isGranted('CREATE')) {
  427. throw new AccessDeniedException();
  428. }
  429. $object = $this->admin->getNewInstance();
  430. $this->admin->setSubject($object);
  431. /** @var $form \Symfony\Component\Form\Form */
  432. $form = $this->admin->getForm();
  433. $form->setData($object);
  434. if ($this->getRestMethod()== 'POST') {
  435. $form->submit($this->get('request'));
  436. $isFormValid = $form->isValid();
  437. // persist if the form was valid and if in preview mode the preview was approved
  438. if ($isFormValid && (!$this->isInPreviewMode() || $this->isPreviewApproved())) {
  439. if (false === $this->admin->isGranted('CREATE', $object)) {
  440. throw new AccessDeniedException();
  441. }
  442. try {
  443. $object = $this->admin->create($object);
  444. if ($this->isXmlHttpRequest()) {
  445. return $this->renderJson(array(
  446. 'result' => 'ok',
  447. 'objectId' => $this->admin->getNormalizedIdentifier($object)
  448. ));
  449. }
  450. $this->addFlash('sonata_flash_success', $this->admin->trans('flash_create_success', array('%name%' => $this->admin->toString($object)), 'SonataAdminBundle'));
  451. // redirect to edit mode
  452. return $this->redirectTo($object);
  453. } catch (ModelManagerException $e) {
  454. $isFormValid = false;
  455. }
  456. }
  457. // show an error message if the form failed validation
  458. if (!$isFormValid) {
  459. if (!$this->isXmlHttpRequest()) {
  460. $this->addFlash('sonata_flash_error', $this->admin->trans('flash_create_error', array('%name%' => $this->admin->toString($object)), 'SonataAdminBundle'));
  461. }
  462. } elseif ($this->isPreviewRequested()) {
  463. // pick the preview template if the form was valid and preview was requested
  464. $templateKey = 'preview';
  465. $this->admin->getShow();
  466. }
  467. }
  468. $view = $form->createView();
  469. // set the theme for the current Admin Form
  470. $this->get('twig')->getExtension('form')->renderer->setTheme($view, $this->admin->getFormTheme());
  471. return $this->render($this->admin->getTemplate($templateKey), array(
  472. 'action' => 'create',
  473. 'form' => $view,
  474. 'object' => $object,
  475. ));
  476. }
  477. /**
  478. * Returns true if the preview is requested to be shown
  479. *
  480. * @return bool
  481. */
  482. protected function isPreviewRequested()
  483. {
  484. return ($this->get('request')->get('btn_preview') !== null);
  485. }
  486. /**
  487. * Returns true if the preview has been approved
  488. *
  489. * @return bool
  490. */
  491. protected function isPreviewApproved()
  492. {
  493. return ($this->get('request')->get('btn_preview_approve') !== null);
  494. }
  495. /**
  496. * Returns true if the request is in the preview workflow
  497. *
  498. * That means either a preview is requested or the preview has already been shown
  499. * and it got approved/declined.
  500. *
  501. * @return bool
  502. */
  503. protected function isInPreviewMode()
  504. {
  505. return $this->admin->supportsPreviewMode()
  506. && ($this->isPreviewRequested()
  507. || $this->isPreviewApproved()
  508. || $this->isPreviewDeclined());
  509. }
  510. /**
  511. * Returns true if the preview has been declined
  512. *
  513. * @return bool
  514. */
  515. protected function isPreviewDeclined()
  516. {
  517. return ($this->get('request')->get('btn_preview_decline') !== null);
  518. }
  519. /**
  520. * Show action
  521. *
  522. * @param int|string|null $id
  523. *
  524. * @return Response
  525. *
  526. * @throws NotFoundHttpException If the object does not exist
  527. * @throws AccessDeniedException If access is not granted
  528. */
  529. public function showAction($id = null)
  530. {
  531. $id = $this->get('request')->get($this->admin->getIdParameter());
  532. $object = $this->admin->getObject($id);
  533. if (!$object) {
  534. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  535. }
  536. if (false === $this->admin->isGranted('VIEW', $object)) {
  537. throw new AccessDeniedException();
  538. }
  539. $this->admin->setSubject($object);
  540. return $this->render($this->admin->getTemplate('show'), array(
  541. 'action' => 'show',
  542. 'object' => $object,
  543. 'elements' => $this->admin->getShow(),
  544. ));
  545. }
  546. /**
  547. * Show history revisions for object
  548. *
  549. * @param int|string|null $id
  550. *
  551. * @return Response
  552. *
  553. * @throws AccessDeniedException If access is not granted
  554. * @throws NotFoundHttpException If the object does not exist or the audit reader is not available
  555. */
  556. public function historyAction($id = null)
  557. {
  558. $id = $this->get('request')->get($this->admin->getIdParameter());
  559. $object = $this->admin->getObject($id);
  560. if (!$object) {
  561. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  562. }
  563. if (false === $this->admin->isGranted('EDIT', $object)) {
  564. throw new AccessDeniedException();
  565. }
  566. $manager = $this->get('sonata.admin.audit.manager');
  567. if (!$manager->hasReader($this->admin->getClass())) {
  568. throw new NotFoundHttpException(sprintf('unable to find the audit reader for class : %s', $this->admin->getClass()));
  569. }
  570. $reader = $manager->getReader($this->admin->getClass());
  571. $revisions = $reader->findRevisions($this->admin->getClass(), $id);
  572. return $this->render($this->admin->getTemplate('history'), array(
  573. 'action' => 'history',
  574. 'object' => $object,
  575. 'revisions' => $revisions,
  576. 'currentRevision' => $revisions ? current($revisions) : false,
  577. ));
  578. }
  579. /**
  580. * View history revision of object
  581. *
  582. * @param int|string|null $id
  583. * @param string|null $revision
  584. *
  585. * @return Response
  586. *
  587. * @throws AccessDeniedException If access is not granted
  588. * @throws NotFoundHttpException If the object or revision does not exist or the audit reader is not available
  589. */
  590. public function historyViewRevisionAction($id = null, $revision = null)
  591. {
  592. $id = $this->get('request')->get($this->admin->getIdParameter());
  593. $object = $this->admin->getObject($id);
  594. if (!$object) {
  595. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  596. }
  597. if (false === $this->admin->isGranted('EDIT', $object)) {
  598. throw new AccessDeniedException();
  599. }
  600. $manager = $this->get('sonata.admin.audit.manager');
  601. if (!$manager->hasReader($this->admin->getClass())) {
  602. throw new NotFoundHttpException(sprintf('unable to find the audit reader for class : %s', $this->admin->getClass()));
  603. }
  604. $reader = $manager->getReader($this->admin->getClass());
  605. // retrieve the revisioned object
  606. $object = $reader->find($this->admin->getClass(), $id, $revision);
  607. if (!$object) {
  608. throw new NotFoundHttpException(sprintf('unable to find the targeted object `%s` from the revision `%s` with classname : `%s`', $id, $revision, $this->admin->getClass()));
  609. }
  610. $this->admin->setSubject($object);
  611. return $this->render($this->admin->getTemplate('show'), array(
  612. 'action' => 'show',
  613. 'object' => $object,
  614. 'elements' => $this->admin->getShow(),
  615. ));
  616. }
  617. /**
  618. * Compare history revisions of object
  619. *
  620. * @param int|string|null $id
  621. * @param int|string|null $base_revision
  622. * @param int|string|null $compare_revision
  623. *
  624. * @return Response
  625. *
  626. * @throws AccessDeniedException If access is not granted
  627. * @throws NotFoundHttpException If the object or revision does not exist or the audit reader is not available
  628. */
  629. public function historyCompareRevisionsAction($id = null, $base_revision = null, $compare_revision = null)
  630. {
  631. if (false === $this->admin->isGranted('EDIT')) {
  632. throw new AccessDeniedException();
  633. }
  634. $id = $this->get('request')->get($this->admin->getIdParameter());
  635. $object = $this->admin->getObject($id);
  636. if (!$object) {
  637. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  638. }
  639. $manager = $this->get('sonata.admin.audit.manager');
  640. if (!$manager->hasReader($this->admin->getClass())) {
  641. throw new NotFoundHttpException(sprintf('unable to find the audit reader for class : %s', $this->admin->getClass()));
  642. }
  643. $reader = $manager->getReader($this->admin->getClass());
  644. // retrieve the base revision
  645. $base_object = $reader->find($this->admin->getClass(), $id, $base_revision);
  646. if (!$base_object) {
  647. throw new NotFoundHttpException(sprintf('unable to find the targeted object `%s` from the revision `%s` with classname : `%s`', $id, $base_revision, $this->admin->getClass()));
  648. }
  649. // retrieve the compare revision
  650. $compare_object = $reader->find($this->admin->getClass(), $id, $compare_revision);
  651. if (!$compare_object) {
  652. throw new NotFoundHttpException(sprintf('unable to find the targeted object `%s` from the revision `%s` with classname : `%s`', $id, $compare_revision, $this->admin->getClass()));
  653. }
  654. $this->admin->setSubject($base_object);
  655. return $this->render($this->admin->getTemplate('show_compare'), array(
  656. 'action' => 'show',
  657. 'object' => $base_object,
  658. 'object_compare' => $compare_object,
  659. 'elements' => $this->admin->getShow()
  660. ));
  661. }
  662. /**
  663. * Export data to specified format
  664. *
  665. * @param Request $request
  666. *
  667. * @return Response
  668. *
  669. * @throws AccessDeniedException If access is not granted
  670. * @throws \RuntimeException If the export format is invalid
  671. */
  672. public function exportAction(Request $request)
  673. {
  674. if (false === $this->admin->isGranted('EXPORT')) {
  675. throw new AccessDeniedException();
  676. }
  677. $format = $request->get('format');
  678. $allowedExportFormats = (array) $this->admin->getExportFormats();
  679. if (!in_array($format, $allowedExportFormats)) {
  680. throw new \RuntimeException(sprintf('Export in format `%s` is not allowed for class: `%s`. Allowed formats are: `%s`', $format, $this->admin->getClass(), implode(', ', $allowedExportFormats)));
  681. }
  682. $filename = sprintf(
  683. 'export_%s_%s.%s',
  684. strtolower(substr($this->admin->getClass(), strripos($this->admin->getClass(), '\\') + 1)),
  685. date('Y_m_d_H_i_s', strtotime('now')),
  686. $format
  687. );
  688. return $this->get('sonata.admin.exporter')->getResponse($format, $filename, $this->admin->getDataSourceIterator());
  689. }
  690. /**
  691. * Gets ACL users
  692. *
  693. * @return \Traversable
  694. */
  695. protected function getAclUsers()
  696. {
  697. $aclUsers = array();
  698. $userManagerServiceName = $this->container->getParameter('sonata.admin.security.acl_user_manager');
  699. if ($userManagerServiceName !== null && $this->has($userManagerServiceName)) {
  700. $userManager = $this->get($userManagerServiceName);
  701. if (method_exists($userManager, 'findUsers')) {
  702. $aclUsers = $userManager->findUsers();
  703. }
  704. }
  705. return is_array($aclUsers) ? new \ArrayIterator($aclUsers) : $aclUsers;
  706. }
  707. /**
  708. * Returns the Response object associated to the acl action
  709. *
  710. * @param int|string|null $id
  711. *
  712. * @return Response|RedirectResponse
  713. *
  714. * @throws AccessDeniedException If access is not granted.
  715. * @throws NotFoundHttpException If the object does not exist or the ACL is not enabled
  716. */
  717. public function aclAction($id = null)
  718. {
  719. if (!$this->admin->isAclEnabled()) {
  720. throw new NotFoundHttpException('ACL are not enabled for this admin');
  721. }
  722. $id = $this->get('request')->get($this->admin->getIdParameter());
  723. $object = $this->admin->getObject($id);
  724. if (!$object) {
  725. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  726. }
  727. if (false === $this->admin->isGranted('MASTER', $object)) {
  728. throw new AccessDeniedException();
  729. }
  730. $this->admin->setSubject($object);
  731. $aclUsers = $this->getAclUsers();
  732. $adminObjectAclManipulator = $this->get('sonata.admin.object.manipulator.acl.admin');
  733. $adminObjectAclData = new AdminObjectAclData(
  734. $this->admin,
  735. $object,
  736. $aclUsers,
  737. $adminObjectAclManipulator->getMaskBuilderClass()
  738. );
  739. $form = $adminObjectAclManipulator->createForm($adminObjectAclData);
  740. $request = $this->getRequest();
  741. if ($request->getMethod() === 'POST') {
  742. $form->submit($request);
  743. if ($form->isValid()) {
  744. $adminObjectAclManipulator->updateAcl($adminObjectAclData);
  745. $this->addFlash('sonata_flash_success', 'flash_acl_edit_success');
  746. return new RedirectResponse($this->admin->generateObjectUrl('acl', $object));
  747. }
  748. }
  749. return $this->render($this->admin->getTemplate('acl'), array(
  750. 'action' => 'acl',
  751. 'permissions' => $adminObjectAclData->getUserPermissions(),
  752. 'object' => $object,
  753. 'users' => $aclUsers,
  754. 'form' => $form->createView()
  755. ));
  756. }
  757. /**
  758. * Adds a flash message for type.
  759. *
  760. * @param string $type
  761. * @param string $message
  762. */
  763. protected function addFlash($type, $message)
  764. {
  765. $this->get('session')
  766. ->getFlashBag()
  767. ->add($type, $message);
  768. }
  769. /**
  770. * Validate CSRF token for action without form
  771. *
  772. * @param string $intention
  773. *
  774. * @throws HttpException
  775. */
  776. protected function validateCsrfToken($intention)
  777. {
  778. if (!$this->container->has('form.csrf_provider')) {
  779. return;
  780. }
  781. if (!$this->container->get('form.csrf_provider')->isCsrfTokenValid($intention, $this->get('request')->request->get('_sonata_csrf_token', false))) {
  782. throw new HttpException(400, 'The csrf token is not valid, CSRF attack?');
  783. }
  784. }
  785. /**
  786. * Get CSRF token
  787. *
  788. * @param string $intention
  789. *
  790. * @return string|false
  791. */
  792. protected function getCsrfToken($intention)
  793. {
  794. if (!$this->container->has('form.csrf_provider')) {
  795. return false;
  796. }
  797. return $this->container->get('form.csrf_provider')->generateCsrfToken($intention);
  798. }
  799. }