CRUDController.php 35 KB

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