CRUDController.php 44 KB

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