CRUDController.php 40 KB

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