CRUDController.php 35 KB

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