CRUDController.php 43 KB

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