CRUDController.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966
  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. $object = $this->admin->update($object);
  270. if ($this->isXmlHttpRequest()) {
  271. return $this->renderJson(array(
  272. 'result' => 'ok',
  273. 'objectId' => $this->admin->getNormalizedIdentifier($object)
  274. ));
  275. }
  276. $this->addFlash('sonata_flash_success', $this->admin->trans('flash_edit_success', array('%name%' => $this->admin->toString($object)), 'SonataAdminBundle'));
  277. // redirect to edit mode
  278. return $this->redirectTo($object);
  279. }
  280. // show an error message if the form failed validation
  281. if (!$isFormValid) {
  282. if (!$this->isXmlHttpRequest()) {
  283. $this->addFlash('sonata_flash_error', $this->admin->trans('flash_edit_error', array('%name%' => $this->admin->toString($object)), 'SonataAdminBundle'));
  284. }
  285. } elseif ($this->isPreviewRequested()) {
  286. // enable the preview template if the form was valid and preview was requested
  287. $templateKey = 'preview';
  288. $this->admin->getShow();
  289. }
  290. }
  291. $view = $form->createView();
  292. // set the theme for the current Admin Form
  293. $this->get('twig')->getExtension('form')->renderer->setTheme($view, $this->admin->getFormTheme());
  294. return $this->render($this->admin->getTemplate($templateKey), array(
  295. 'action' => 'edit',
  296. 'form' => $view,
  297. 'object' => $object,
  298. ));
  299. }
  300. /**
  301. * Redirect the user depend on this choice
  302. *
  303. * @param object $object
  304. *
  305. * @return RedirectResponse
  306. */
  307. protected function redirectTo($object)
  308. {
  309. $url = false;
  310. if (null !== $this->get('request')->get('btn_update_and_list')) {
  311. $url = $this->admin->generateUrl('list');
  312. }
  313. if (null !== $this->get('request')->get('btn_create_and_list')) {
  314. $url = $this->admin->generateUrl('list');
  315. }
  316. if (null !== $this->get('request')->get('btn_create_and_create')) {
  317. $params = array();
  318. if ($this->admin->hasActiveSubClass()) {
  319. $params['subclass'] = $this->get('request')->get('subclass');
  320. }
  321. $url = $this->admin->generateUrl('create', $params);
  322. }
  323. if ($this->getRestMethod() == 'DELETE') {
  324. $url = $this->admin->generateUrl('list');
  325. }
  326. if (!$url) {
  327. $url = $this->admin->generateObjectUrl('edit', $object);
  328. }
  329. return new RedirectResponse($url);
  330. }
  331. /**
  332. * Batch action
  333. *
  334. * @return Response|RedirectResponse
  335. *
  336. * @throws NotFoundHttpException If the HTTP method is not POST
  337. * @throws \RuntimeException If the batch action is not defined
  338. */
  339. public function batchAction()
  340. {
  341. $restMethod = $this->getRestMethod();
  342. if ('POST' !== $restMethod) {
  343. throw $this->createNotFoundException(sprintf('Invalid request type "%s", POST expected', $restMethod));
  344. }
  345. // check the csrf token
  346. $this->validateCsrfToken('sonata.batch');
  347. $confirmation = $this->get('request')->get('confirmation', false);
  348. if ($data = json_decode($this->get('request')->get('data'), true)) {
  349. $action = $data['action'];
  350. $idx = $data['idx'];
  351. $allElements = $data['all_elements'];
  352. $this->get('request')->request->replace($data);
  353. } else {
  354. $this->get('request')->request->set('idx', $this->get('request')->get('idx', array()));
  355. $this->get('request')->request->set('all_elements', $this->get('request')->get('all_elements', false));
  356. $action = $this->get('request')->get('action');
  357. $idx = $this->get('request')->get('idx');
  358. $allElements = $this->get('request')->get('all_elements');
  359. $data = $this->get('request')->request->all();
  360. unset($data['_sonata_csrf_token']);
  361. }
  362. $batchActions = $this->admin->getBatchActions();
  363. if (!array_key_exists($action, $batchActions)) {
  364. throw new \RuntimeException(sprintf('The `%s` batch action is not defined', $action));
  365. }
  366. $camelizedAction = BaseFieldDescription::camelize($action);
  367. $isRelevantAction = sprintf('batchAction%sIsRelevant', ucfirst($camelizedAction));
  368. if (method_exists($this, $isRelevantAction)) {
  369. $nonRelevantMessage = call_user_func(array($this, $isRelevantAction), $idx, $allElements);
  370. } else {
  371. $nonRelevantMessage = count($idx) != 0 || $allElements; // at least one item is selected
  372. }
  373. if (!$nonRelevantMessage) { // default non relevant message (if false of null)
  374. $nonRelevantMessage = 'flash_batch_empty';
  375. }
  376. $datagrid = $this->admin->getDatagrid();
  377. $datagrid->buildPager();
  378. if (true !== $nonRelevantMessage) {
  379. $this->addFlash('sonata_flash_info', $nonRelevantMessage);
  380. return new RedirectResponse($this->admin->generateUrl('list', array('filter' => $this->admin->getFilterParameters())));
  381. }
  382. $askConfirmation = isset($batchActions[$action]['ask_confirmation']) ? $batchActions[$action]['ask_confirmation'] : true;
  383. if ($askConfirmation && $confirmation != 'ok') {
  384. $actionLabel = $this->admin->trans($this->admin->getTranslationLabel($action, 'action'));
  385. $formView = $datagrid->getForm()->createView();
  386. return $this->render($this->admin->getTemplate('batch_confirmation'), array(
  387. 'action' => 'list',
  388. 'action_label' => $actionLabel,
  389. 'datagrid' => $datagrid,
  390. 'form' => $formView,
  391. 'data' => $data,
  392. 'csrf_token' => $this->getCsrfToken('sonata.batch'),
  393. ));
  394. }
  395. // execute the action, batchActionXxxxx
  396. $finalAction = sprintf('batchAction%s', ucfirst($camelizedAction));
  397. if (!method_exists($this, $finalAction)) {
  398. throw new \RuntimeException(sprintf('A `%s::%s` method must be created', get_class($this), $finalAction));
  399. }
  400. $query = $datagrid->getQuery();
  401. $query->setFirstResult(null);
  402. $query->setMaxResults(null);
  403. $this->admin->preBatchAction($action, $query, $idx, $allElements);
  404. if (count($idx) > 0) {
  405. $this->admin->getModelManager()->addIdentifiersToQuery($this->admin->getClass(), $query, $idx);
  406. } elseif (!$allElements) {
  407. $query = null;
  408. }
  409. return call_user_func(array($this, $finalAction), $query);
  410. }
  411. /**
  412. * Create action
  413. *
  414. * @return Response
  415. *
  416. * @throws AccessDeniedException If access is not granted
  417. */
  418. public function createAction()
  419. {
  420. // the key used to lookup the template
  421. $templateKey = 'edit';
  422. if (false === $this->admin->isGranted('CREATE')) {
  423. throw new AccessDeniedException();
  424. }
  425. $object = $this->admin->getNewInstance();
  426. $this->admin->setSubject($object);
  427. /** @var $form \Symfony\Component\Form\Form */
  428. $form = $this->admin->getForm();
  429. $form->setData($object);
  430. if ($this->getRestMethod()== 'POST') {
  431. $form->submit($this->get('request'));
  432. $isFormValid = $form->isValid();
  433. // persist if the form was valid and if in preview mode the preview was approved
  434. if ($isFormValid && (!$this->isInPreviewMode() || $this->isPreviewApproved())) {
  435. if (false === $this->admin->isGranted('CREATE', $object)) {
  436. throw new AccessDeniedException();
  437. }
  438. $object = $this->admin->create($object);
  439. if ($this->isXmlHttpRequest()) {
  440. return $this->renderJson(array(
  441. 'result' => 'ok',
  442. 'objectId' => $this->admin->getNormalizedIdentifier($object)
  443. ));
  444. }
  445. $this->addFlash('sonata_flash_success', $this->admin->trans('flash_create_success', array('%name%' => $this->admin->toString($object)), 'SonataAdminBundle'));
  446. // redirect to edit mode
  447. return $this->redirectTo($object);
  448. }
  449. // show an error message if the form failed validation
  450. if (!$isFormValid) {
  451. if (!$this->isXmlHttpRequest()) {
  452. $this->addFlash('sonata_flash_error', $this->admin->trans('flash_create_error', array('%name%' => $this->admin->toString($object)), 'SonataAdminBundle'));
  453. }
  454. } elseif ($this->isPreviewRequested()) {
  455. // pick the preview template if the form was valid and preview was requested
  456. $templateKey = 'preview';
  457. $this->admin->getShow();
  458. }
  459. }
  460. $view = $form->createView();
  461. // set the theme for the current Admin Form
  462. $this->get('twig')->getExtension('form')->renderer->setTheme($view, $this->admin->getFormTheme());
  463. return $this->render($this->admin->getTemplate($templateKey), array(
  464. 'action' => 'create',
  465. 'form' => $view,
  466. 'object' => $object,
  467. ));
  468. }
  469. /**
  470. * Returns true if the preview is requested to be shown
  471. *
  472. * @return bool
  473. */
  474. protected function isPreviewRequested()
  475. {
  476. return ($this->get('request')->get('btn_preview') !== null);
  477. }
  478. /**
  479. * Returns true if the preview has been approved
  480. *
  481. * @return bool
  482. */
  483. protected function isPreviewApproved()
  484. {
  485. return ($this->get('request')->get('btn_preview_approve') !== null);
  486. }
  487. /**
  488. * Returns true if the request is in the preview workflow
  489. *
  490. * That means either a preview is requested or the preview has already been shown
  491. * and it got approved/declined.
  492. *
  493. * @return bool
  494. */
  495. protected function isInPreviewMode()
  496. {
  497. return $this->admin->supportsPreviewMode()
  498. && ($this->isPreviewRequested()
  499. || $this->isPreviewApproved()
  500. || $this->isPreviewDeclined());
  501. }
  502. /**
  503. * Returns true if the preview has been declined
  504. *
  505. * @return bool
  506. */
  507. protected function isPreviewDeclined()
  508. {
  509. return ($this->get('request')->get('btn_preview_decline') !== null);
  510. }
  511. /**
  512. * Show action
  513. *
  514. * @param int|string|null $id
  515. *
  516. * @return Response
  517. *
  518. * @throws NotFoundHttpException If the object does not exist
  519. * @throws AccessDeniedException If access is not granted
  520. */
  521. public function showAction($id = null)
  522. {
  523. $id = $this->get('request')->get($this->admin->getIdParameter());
  524. $object = $this->admin->getObject($id);
  525. if (!$object) {
  526. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  527. }
  528. if (false === $this->admin->isGranted('VIEW', $object)) {
  529. throw new AccessDeniedException();
  530. }
  531. $this->admin->setSubject($object);
  532. return $this->render($this->admin->getTemplate('show'), array(
  533. 'action' => 'show',
  534. 'object' => $object,
  535. 'elements' => $this->admin->getShow(),
  536. ));
  537. }
  538. /**
  539. * Show history revisions for object
  540. *
  541. * @param int|string|null $id
  542. *
  543. * @return Response
  544. *
  545. * @throws AccessDeniedException If access is not granted
  546. * @throws NotFoundHttpException If the object does not exist or the audit reader is not available
  547. */
  548. public function historyAction($id = null)
  549. {
  550. if (false === $this->admin->isGranted('EDIT')) {
  551. throw new AccessDeniedException();
  552. }
  553. $id = $this->get('request')->get($this->admin->getIdParameter());
  554. $object = $this->admin->getObject($id);
  555. if (!$object) {
  556. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  557. }
  558. $manager = $this->get('sonata.admin.audit.manager');
  559. if (!$manager->hasReader($this->admin->getClass())) {
  560. throw new NotFoundHttpException(sprintf('unable to find the audit reader for class : %s', $this->admin->getClass()));
  561. }
  562. $reader = $manager->getReader($this->admin->getClass());
  563. $revisions = $reader->findRevisions($this->admin->getClass(), $id);
  564. return $this->render($this->admin->getTemplate('history'), array(
  565. 'action' => 'history',
  566. 'object' => $object,
  567. 'revisions' => $revisions,
  568. 'currentRevision' => $revisions ? current($revisions) : false,
  569. ));
  570. }
  571. /**
  572. * View history revision of object
  573. *
  574. * @param int|string|null $id
  575. * @param string|null $revision
  576. *
  577. * @return Response
  578. *
  579. * @throws AccessDeniedException If access is not granted
  580. * @throws NotFoundHttpException If the object or revision does not exist or the audit reader is not available
  581. */
  582. public function historyViewRevisionAction($id = null, $revision = null)
  583. {
  584. if (false === $this->admin->isGranted('EDIT')) {
  585. throw new AccessDeniedException();
  586. }
  587. $id = $this->get('request')->get($this->admin->getIdParameter());
  588. $object = $this->admin->getObject($id);
  589. if (!$object) {
  590. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  591. }
  592. $manager = $this->get('sonata.admin.audit.manager');
  593. if (!$manager->hasReader($this->admin->getClass())) {
  594. throw new NotFoundHttpException(sprintf('unable to find the audit reader for class : %s', $this->admin->getClass()));
  595. }
  596. $reader = $manager->getReader($this->admin->getClass());
  597. // retrieve the revisioned object
  598. $object = $reader->find($this->admin->getClass(), $id, $revision);
  599. if (!$object) {
  600. throw new NotFoundHttpException(sprintf('unable to find the targeted object `%s` from the revision `%s` with classname : `%s`', $id, $revision, $this->admin->getClass()));
  601. }
  602. $this->admin->setSubject($object);
  603. return $this->render($this->admin->getTemplate('show'), array(
  604. 'action' => 'show',
  605. 'object' => $object,
  606. 'elements' => $this->admin->getShow(),
  607. ));
  608. }
  609. /**
  610. * Compare history revisions of object
  611. *
  612. * @param int|string|null $id
  613. * @param int|string|null $base_revision
  614. * @param int|string|null $compare_revision
  615. *
  616. * @return Response
  617. *
  618. * @throws AccessDeniedException If access is not granted
  619. * @throws NotFoundHttpException If the object or revision does not exist or the audit reader is not available
  620. */
  621. public function historyCompareRevisionsAction($id = null, $base_revision = null, $compare_revision = null)
  622. {
  623. if (false === $this->admin->isGranted('EDIT')) {
  624. throw new AccessDeniedException();
  625. }
  626. $id = $this->get('request')->get($this->admin->getIdParameter());
  627. $object = $this->admin->getObject($id);
  628. if (!$object) {
  629. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  630. }
  631. $manager = $this->get('sonata.admin.audit.manager');
  632. if (!$manager->hasReader($this->admin->getClass())) {
  633. throw new NotFoundHttpException(sprintf('unable to find the audit reader for class : %s', $this->admin->getClass()));
  634. }
  635. $reader = $manager->getReader($this->admin->getClass());
  636. // retrieve the base revision
  637. $base_object = $reader->find($this->admin->getClass(), $id, $base_revision);
  638. if (!$base_object) {
  639. throw new NotFoundHttpException(sprintf('unable to find the targeted object `%s` from the revision `%s` with classname : `%s`', $id, $base_revision, $this->admin->getClass()));
  640. }
  641. // retrieve the compare revision
  642. $compare_object = $reader->find($this->admin->getClass(), $id, $compare_revision);
  643. if (!$compare_object) {
  644. throw new NotFoundHttpException(sprintf('unable to find the targeted object `%s` from the revision `%s` with classname : `%s`', $id, $compare_revision, $this->admin->getClass()));
  645. }
  646. $this->admin->setSubject($base_object);
  647. return $this->render($this->admin->getTemplate('show_compare'), array(
  648. 'action' => 'show',
  649. 'object' => $base_object,
  650. 'object_compare' => $compare_object,
  651. 'elements' => $this->admin->getShow()
  652. ));
  653. }
  654. /**
  655. * Export data to specified format
  656. *
  657. * @param Request $request
  658. *
  659. * @return Response
  660. *
  661. * @throws AccessDeniedException If access is not granted
  662. * @throws \RuntimeException If the export format is invalid
  663. */
  664. public function exportAction(Request $request)
  665. {
  666. if (false === $this->admin->isGranted('EXPORT')) {
  667. throw new AccessDeniedException();
  668. }
  669. $format = $request->get('format');
  670. $allowedExportFormats = (array) $this->admin->getExportFormats();
  671. if (!in_array($format, $allowedExportFormats)) {
  672. throw new \RuntimeException(sprintf('Export in format `%s` is not allowed for class: `%s`. Allowed formats are: `%s`', $format, $this->admin->getClass(), implode(', ', $allowedExportFormats)));
  673. }
  674. $filename = sprintf(
  675. 'export_%s_%s.%s',
  676. strtolower(substr($this->admin->getClass(), strripos($this->admin->getClass(), '\\') + 1)),
  677. date('Y_m_d_H_i_s', strtotime('now')),
  678. $format
  679. );
  680. return $this->get('sonata.admin.exporter')->getResponse($format, $filename, $this->admin->getDataSourceIterator());
  681. }
  682. /**
  683. * Gets ACL users
  684. *
  685. * @return \Traversable
  686. */
  687. protected function getAclUsers()
  688. {
  689. $aclUsers = array();
  690. $userManagerServiceName = $this->container->getParameter('sonata.admin.security.acl_user_manager');
  691. if ($userManagerServiceName !== null && $this->has($userManagerServiceName)) {
  692. $userManager = $this->get($userManagerServiceName);
  693. if (method_exists($userManager, 'findUsers')) {
  694. $aclUsers = $userManager->findUsers();
  695. }
  696. }
  697. return is_array($aclUsers) ? new \ArrayIterator($aclUsers) : $aclUsers;
  698. }
  699. /**
  700. * Returns the Response object associated to the acl action
  701. *
  702. * @param int|string|null $id
  703. *
  704. * @return Response|RedirectResponse
  705. *
  706. * @throws AccessDeniedException If access is not granted.
  707. * @throws NotFoundHttpException If the object does not exist or the ACL is not enabled
  708. */
  709. public function aclAction($id = null)
  710. {
  711. if (!$this->admin->isAclEnabled()) {
  712. throw new NotFoundHttpException('ACL are not enabled for this admin');
  713. }
  714. $id = $this->get('request')->get($this->admin->getIdParameter());
  715. $object = $this->admin->getObject($id);
  716. if (!$object) {
  717. throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
  718. }
  719. if (false === $this->admin->isGranted('MASTER', $object)) {
  720. throw new AccessDeniedException();
  721. }
  722. $this->admin->setSubject($object);
  723. $aclUsers = $this->getAclUsers();
  724. $adminObjectAclManipulator = $this->get('sonata.admin.object.manipulator.acl.admin');
  725. $adminObjectAclData = new AdminObjectAclData(
  726. $this->admin,
  727. $object,
  728. $aclUsers,
  729. $adminObjectAclManipulator->getMaskBuilderClass()
  730. );
  731. $form = $adminObjectAclManipulator->createForm($adminObjectAclData);
  732. $request = $this->getRequest();
  733. if ($request->getMethod() === 'POST') {
  734. $form->submit($request);
  735. if ($form->isValid()) {
  736. $adminObjectAclManipulator->updateAcl($adminObjectAclData);
  737. $this->addFlash('sonata_flash_success', 'flash_acl_edit_success');
  738. return new RedirectResponse($this->admin->generateObjectUrl('acl', $object));
  739. }
  740. }
  741. return $this->render($this->admin->getTemplate('acl'), array(
  742. 'action' => 'acl',
  743. 'permissions' => $adminObjectAclData->getUserPermissions(),
  744. 'object' => $object,
  745. 'users' => $aclUsers,
  746. 'form' => $form->createView()
  747. ));
  748. }
  749. /**
  750. * Adds a flash message for type.
  751. *
  752. * @param string $type
  753. * @param string $message
  754. */
  755. protected function addFlash($type, $message)
  756. {
  757. $this->get('session')
  758. ->getFlashBag()
  759. ->add($type, $message);
  760. }
  761. /**
  762. * Validate CSRF token for action without form
  763. *
  764. * @param string $intention
  765. *
  766. * @throws HttpException
  767. */
  768. protected function validateCsrfToken($intention)
  769. {
  770. if (!$this->container->has('form.csrf_provider')) {
  771. return;
  772. }
  773. if (!$this->container->get('form.csrf_provider')->isCsrfTokenValid($intention, $this->get('request')->request->get('_sonata_csrf_token', false))) {
  774. throw new HttpException(400, 'The csrf token is not valid, CSRF attack?');
  775. }
  776. }
  777. /**
  778. * Get CSRF token
  779. *
  780. * @param string $intention
  781. *
  782. * @return string|false
  783. */
  784. protected function getCsrfToken($intention)
  785. {
  786. if (!$this->container->has('form.csrf_provider')) {
  787. return false;
  788. }
  789. return $this->container->get('form.csrf_provider')->generateCsrfToken($intention);
  790. }
  791. }