CRUDController.php 38 KB

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