CRUDController.php 43 KB

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