CRUDController.php 37 KB

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