CRUDController.php 42 KB

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