CRUDController.php 36 KB

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