CRUDController.php 44 KB

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