CRUDController.php 43 KB

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