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