CRUDController.php 35 KB

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