CRUDController.php 45 KB

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