CRUDController.php 44 KB

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