CRUDController.php 43 KB

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