fix folder name

This commit is contained in:
2021-03-18 13:37:13 +01:00
parent a2f6773f5a
commit eaa0ad925f
1578 changed files with 0 additions and 0 deletions

View File

@@ -0,0 +1,54 @@
<?php
/*
* Chill is a software for social workers
*
* Copyright (C) 2014, Champs Libres Cooperative SCRLFS, <http://www.champs-libres.coop>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Chill\MainBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
/**
* Class AdminController
*
* @package Chill\MainBundle\Controller
* @author julien.fastre@champs-libres.coop
* @author marc@champs-libres.coop
*/
class AdminController extends AbstractController
{
public function indexAction($menu = 'admin',
$header_title = 'views.Main.admin.index.header_title',
$page_title = 'views.Main.admin.index.page_title') {
return $this->render('@ChillMain/Admin/layout.html.twig');
}
public function indexPermissionsAction()
{
return $this->render('@ChillMain/Admin/layout_permissions.html.twig');
}
public function configurationWarningsAction()
{
$alertManager = $this->get('chill_main.configuration_alert_manager');
}
}

View File

@@ -0,0 +1,20 @@
<?php
namespace Chill\MainBundle\Controller;
use Chill\MainBundle\CRUD\Controller\CRUDController;
use Chill\MainBundle\Entity\Country;
use Chill\MainBundle\Pagination\PaginatorFactory;
/**
*
*
*/
class AdminCountryCRUDController extends CRUDController
{
function __construct(PaginatorFactory $paginator)
{
$this->paginatorFactory = $paginator;
}
}

View File

@@ -0,0 +1,179 @@
<?php
namespace Chill\MainBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Chill\MainBundle\Entity\Center;
use Chill\MainBundle\Form\CenterType;
/**
* Class CenterController
*
* @package Chill\MainBundle\Controller
*/
class CenterController extends AbstractController
{
/**
* Lists all Center entities.
*
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('ChillMainBundle:Center')->findAll();
return $this->render('@ChillMain/Center/index.html.twig', array(
'entities' => $entities,
));
}
/**
* Creates a new Center entity.
*
*/
public function createAction(Request $request)
{
$center = new Center();
$form = $this->createCreateForm($center);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($center);
$em->flush();
return $this->redirect($this->generateUrl('admin_center_show', array('id' => $center->getId())));
}
return $this->render('@ChillMain/Center/new.html.twig', array(
'entity' => $center,
'form' => $form->createView(),
));
}
/**
* Creates a form to create a Center entity.
*
* @param Center $center The entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createCreateForm(Center $center)
{
$form = $this->createForm(CenterType::class, $center, array(
'action' => $this->generateUrl('admin_center_create'),
'method' => 'POST',
));
$form->add('submit', SubmitType::class, array('label' => 'Create'));
return $form;
}
/**
* Displays a form to create a new Center entity.
*
*/
public function newAction()
{
$center = new Center();
$form = $this->createCreateForm($center);
return $this->render('@ChillMain/Center/new.html.twig', array(
'entity' => $center,
'form' => $form->createView(),
));
}
/**
* Finds and displays a Center entity.
*
*/
public function showAction($id)
{
$em = $this->getDoctrine()->getManager();
$center = $em->getRepository('ChillMainBundle:Center')->find($id);
if (!$center) {
throw $this->createNotFoundException('Unable to find Center entity.');
}
return $this->render('@ChillMain/Center/show.html.twig', array(
'entity' => $center
));
}
/**
* Displays a form to edit an existing Center entity.
*
*/
public function editAction($id)
{
$em = $this->getDoctrine()->getManager();
$center = $em->getRepository('ChillMainBundle:Center')->find($id);
if (!$center) {
throw $this->createNotFoundException('Unable to find Center entity.');
}
$editForm = $this->createEditForm($center);
return $this->render('@ChillMain/Center/edit.html.twig', array(
'entity' => $center,
'edit_form' => $editForm->createView()
));
}
/**
* Creates a form to edit a Center entity.
*
* @param Center $center The entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createEditForm(Center $center)
{
$form = $this->createForm(CenterType::class, $center, array(
'action' => $this->generateUrl('admin_center_update', array('id' => $center->getId())),
'method' => 'PUT',
));
$form->add('submit', SubmitType::class, array('label' => 'Update'));
return $form;
}
/**
* Edits an existing Center entity.
*
*/
public function updateAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$center = $em->getRepository('ChillMainBundle:Center')->find($id);
if (!$center) {
throw $this->createNotFoundException('Unable to find Center entity.');
}
$editForm = $this->createEditForm($center);
$editForm->handleRequest($request);
if ($editForm->isValid()) {
$em->flush();
return $this->redirect($this->generateUrl('admin_center_edit', array('id' => $id)));
}
return $this->render('@ChillMain/Center/edit.html.twig', array(
'entity' => $center,
'edit_form' => $editForm->createView()
));
}
}

View File

@@ -0,0 +1,86 @@
<?php
namespace Chill\MainBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
/**
* Class DefaultController
*
* @package Chill\MainBundle\Controller
*/
class DefaultController extends AbstractController
{
public function indexAction()
{
if ($this->isGranted('ROLE_ADMIN')) {
return $this->redirectToRoute('chill_main_admin_central', [], 302);
}
return $this->render('@ChillMain/layout.html.twig');
}
public function indexWithoutLocaleAction()
{
return $this->redirect($this->generateUrl('chill_main_homepage'));
}
public function testAction()
{
return $this->render('@ChillMain/Tabs/index.html.twig', [
'tabs' => [
'test1' => [
[
'name' => "Link 1",
'content' => "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Vitae auctor eu augue ut. Elementum nisi quis eleifend quam. Faucibus purus in massa tempor nec. Turpis massa sed elementum tempus egestas sed sed risus. Etiam sit amet nisl purus in mollis nunc sed id. Enim nunc faucibus a pellentesque sit amet porttitor eget. Risus nec feugiat in fermentum posuere. Augue mauris augue neque gravida. Sollicitudin aliquam ultrices sagittis orci a scelerisque purus semper eget. Id leo in vitae turpis massa sed elementum tempus egestas. Mauris commodo quis imperdiet massa. Fames ac turpis egestas integer eget aliquet nibh praesent. Urna porttitor rhoncus dolor purus non enim praesent elementum. Donec enim diam vulputate ut pharetra sit. Auctor neque vitae tempus quam. Mattis rhoncus urna neque viverra justo nec ultrices.",
],
[
'name' => "Link 2",
'content' => "Dui sapien eget mi proin sed libero. Neque volutpat ac tincidunt vitae semper quis lectus nulla. Turpis nunc eget lorem dolor. Phasellus egestas tellus rutrum tellus. Diam sit amet nisl suscipit adipiscing bibendum est ultricies integer. Duis ultricies lacus sed turpis tincidunt id. Nisl suscipit adipiscing bibendum est ultricies integer. Elementum nibh tellus molestie nunc non blandit massa enim. Faucibus in ornare quam viverra orci sagittis eu. Neque volutpat ac tincidunt vitae semper quis lectus nulla. Accumsan sit amet nulla facilisi morbi. Leo vel fringilla est ullamcorper eget nulla facilisi etiam dignissim. Amet est placerat in egestas erat imperdiet sed euismod. Quis auctor elit sed vulputate mi. Mauris nunc congue nisi vitae suscipit tellus mauris a diam. At volutpat diam ut venenatis. Facilisis gravida neque convallis a cras semper.",
],
[
'name' => "Link 3",
'content' => "In ornare quam viverra orci sagittis eu volutpat. Ac tincidunt vitae semper quis lectus nulla at volutpat. Placerat duis ultricies lacus sed turpis tincidunt. Augue interdum velit euismod in pellentesque. Felis eget nunc lobortis mattis aliquam. Volutpat lacus laoreet non curabitur gravida arcu. Gravida cum sociis natoque penatibus et magnis dis parturient montes. Nisl pretium fusce id velit ut tortor. Nunc scelerisque viverra mauris in aliquam sem fringilla ut. Magna eget est lorem ipsum dolor sit. Non consectetur a erat nam at lectus urna. Eget est lorem ipsum dolor sit amet consectetur adipiscing elit. Sed velit dignissim sodales ut.",
],
[
'name' => "Link 4",
'content' => "Ut tellus elementum sagittis vitae et. Vitae purus faucibus ornare suspendisse sed nisi lacus sed viverra. Hendrerit gravida rutrum quisque non tellus orci ac auctor augue. Eleifend quam adipiscing vitae proin sagittis nisl rhoncus mattis rhoncus. Dictumst quisque sagittis purus sit. Suspendisse sed nisi lacus sed viverra. Pretium quam vulputate dignissim suspendisse in est ante. Id eu nisl nunc mi ipsum. Ut venenatis tellus in metus vulputate. Ut morbi tincidunt augue interdum velit euismod.",
],
[
'name' => "Link 5",
'content' => "Vel elit scelerisque mauris pellentesque pulvinar. Ornare suspendisse sed nisi lacus sed viverra tellus. Massa tincidunt dui ut ornare lectus sit. Congue nisi vitae suscipit tellus mauris a diam. At auctor urna nunc id cursus metus aliquam. Viverra accumsan in nisl nisi scelerisque eu ultrices vitae. Mattis aliquam faucibus purus in massa tempor nec feugiat. Et leo duis ut diam quam. Auctor augue mauris augue neque. Purus ut faucibus pulvinar elementum integer enim neque volutpat. Scelerisque felis imperdiet proin fermentum leo. Diam sit amet nisl suscipit adipiscing bibendum est ultricies. Consectetur libero id faucibus nisl tincidunt. Vel fringilla est ullamcorper eget nulla facilisi. Pharetra diam sit amet nisl suscipit adipiscing. Dignissim diam quis enim lobortis. Auctor eu augue ut lectus arcu bibendum at varius.",
]
],
'test2' => [
[
'name' => "Link 1",
'link' => "http://localhost",
'content' => "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Vitae auctor eu augue ut. Elementum nisi quis eleifend quam. Faucibus purus in massa tempor nec. Turpis massa sed elementum tempus egestas sed sed risus. Etiam sit amet nisl purus in mollis nunc sed id. Enim nunc faucibus a pellentesque sit amet porttitor eget. Risus nec feugiat in fermentum posuere. Augue mauris augue neque gravida. Sollicitudin aliquam ultrices sagittis orci a scelerisque purus semper eget. Id leo in vitae turpis massa sed elementum tempus egestas. Mauris commodo quis imperdiet massa. Fames ac turpis egestas integer eget aliquet nibh praesent. Urna porttitor rhoncus dolor purus non enim praesent elementum. Donec enim diam vulputate ut pharetra sit. Auctor neque vitae tempus quam. Mattis rhoncus urna neque viverra justo nec ultrices.",
],
[
'name' => "Link 2",
//'link' => "http://localhost",
'content' => "Dui sapien eget mi proin sed libero. Neque volutpat ac tincidunt vitae semper quis lectus nulla. Turpis nunc eget lorem dolor. Phasellus egestas tellus rutrum tellus. Diam sit amet nisl suscipit adipiscing bibendum est ultricies integer. Duis ultricies lacus sed turpis tincidunt id. Nisl suscipit adipiscing bibendum est ultricies integer. Elementum nibh tellus molestie nunc non blandit massa enim. Faucibus in ornare quam viverra orci sagittis eu. Neque volutpat ac tincidunt vitae semper quis lectus nulla. Accumsan sit amet nulla facilisi morbi. Leo vel fringilla est ullamcorper eget nulla facilisi etiam dignissim. Amet est placerat in egestas erat imperdiet sed euismod. Quis auctor elit sed vulputate mi. Mauris nunc congue nisi vitae suscipit tellus mauris a diam. At volutpat diam ut venenatis. Facilisis gravida neque convallis a cras semper.",
],
[
'name' => "Link 3",
//'link' => "http://localhost",
'content' => "In ornare quam viverra orci sagittis eu volutpat. Ac tincidunt vitae semper quis lectus nulla at volutpat. Placerat duis ultricies lacus sed turpis tincidunt. Augue interdum velit euismod in pellentesque. Felis eget nunc lobortis mattis aliquam. Volutpat lacus laoreet non curabitur gravida arcu. Gravida cum sociis natoque penatibus et magnis dis parturient montes. Nisl pretium fusce id velit ut tortor. Nunc scelerisque viverra mauris in aliquam sem fringilla ut. Magna eget est lorem ipsum dolor sit. Non consectetur a erat nam at lectus urna. Eget est lorem ipsum dolor sit amet consectetur adipiscing elit. Sed velit dignissim sodales ut.",
],
[
'name' => "Link 4",
'link' => "http://localhost",
//'content' => "Ut tellus elementum sagittis vitae et. Vitae purus faucibus ornare suspendisse sed nisi lacus sed viverra. Hendrerit gravida rutrum quisque non tellus orci ac auctor augue. Eleifend quam adipiscing vitae proin sagittis nisl rhoncus mattis rhoncus. Dictumst quisque sagittis purus sit. Suspendisse sed nisi lacus sed viverra. Pretium quam vulputate dignissim suspendisse in est ante. Id eu nisl nunc mi ipsum. Ut venenatis tellus in metus vulputate. Ut morbi tincidunt augue interdum velit euismod.",
],
[
'name' => "Link 5",
//'link' => "http://localhost",
'content' => "Vel elit scelerisque mauris pellentesque pulvinar. Ornare suspendisse sed nisi lacus sed viverra tellus. Massa tincidunt dui ut ornare lectus sit. Congue nisi vitae suscipit tellus mauris a diam. At auctor urna nunc id cursus metus aliquam. Viverra accumsan in nisl nisi scelerisque eu ultrices vitae. Mattis aliquam faucibus purus in massa tempor nec feugiat. Et leo duis ut diam quam. Auctor augue mauris augue neque. Purus ut faucibus pulvinar elementum integer enim neque volutpat. Scelerisque felis imperdiet proin fermentum leo. Diam sit amet nisl suscipit adipiscing bibendum est ultricies. Consectetur libero id faucibus nisl tincidunt. Vel fringilla est ullamcorper eget nulla facilisi. Pharetra diam sit amet nisl suscipit adipiscing. Dignissim diam quis enim lobortis. Auctor eu augue ut lectus arcu bibendum at varius.",
]
]
]
]);
}
}

View File

@@ -0,0 +1,549 @@
<?php
/*
* Chill is a software for social workers
*
* Copyright (C) 2014-2015, Champs Libres Cooperative SCRLFS,
* <http://www.champs-libres.coop>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Chill\MainBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Chill\MainBundle\Form\Type\Export\ExportType;
use Chill\MainBundle\Form\Type\Export\FormatterType;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Chill\MainBundle\Form\Type\Export\PickCenterType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Chill\MainBundle\Export\ExportManager;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Form\FormFactoryInterface;
use Chill\MainBundle\Redis\ChillRedis;
use Symfony\Component\Translation\TranslatorInterface;
/**
* Class ExportController
* Controller used for exporting data.
*
* @package Chill\MainBundle\Controller
*/
class ExportController extends AbstractController
{
/**
*
* @var ExportManager
*/
protected $exportManager;
/**
*
* @var LoggerInterface
*/
protected $logger;
/**
*
* @var SessionInterface
*/
protected $session;
/**
*
* @var FormFactoryInterface
*/
protected $formFactory;
/**
*
* @var ChillRedis
*/
protected $redis;
/**
*
* @var TranslatorInterface
*/
protected $translator;
public function __construct(
ChillRedis $chillRedis,
ExportManager $exportManager,
FormFactoryInterface $formFactory,
LoggerInterface $logger,
SessionInterface $session,
TranslatorInterface $translator
) {
$this->redis = $chillRedis;
$this->exportManager = $exportManager;
$this->formFactory = $formFactory;
$this->logger = $logger;
$this->session = $session;
$this->translator = $translator;
}
/**
* Render the list of available exports
*
* @param Request $request
* @return \Symfony\Component\HttpFoundation\Response
*/
public function indexAction(Request $request)
{
$exportManager = $this->exportManager;
$exports = $exportManager->getExportsGrouped(true);
return $this->render('@ChillMain/Export/layout.html.twig', array(
'grouped_exports' => $exports
));
}
/**
* handle the step to build a query for an export
*
* This action has three steps :
*
* 1.'export', the export form. When the form is posted, the data is stored
* in the session (if valid), and then a redirection is done to next step.
* 2. 'formatter', the formatter form. When the form is posted, the data is
* stored in the session (if valid), and then a redirection is done to next step.
* 3. 'generate': gather data from session from the previous steps, and
* make a redirection to the "generate" action with data in query (HTTP GET)
*
* @param string $request
* @param Request $alias
* @return \Symfony\Component\HttpFoundation\Response
*/
public function newAction(Request $request, $alias)
{
// first check for ACL
$exportManager = $this->exportManager;
$export = $exportManager->getExport($alias);
if ($exportManager->isGrantedForElement($export) === FALSE) {
throw $this->createAccessDeniedException('The user does not have access to this export');
}
$step = $request->query->getAlpha('step', 'centers');
switch ($step) {
case 'centers':
return $this->selectCentersStep($request, $export, $alias);
case 'export':
return $this->exportFormStep($request, $export, $alias);
break;
case 'formatter':
return $this->formatterFormStep($request, $export, $alias);
break;
case 'generate':
return $this->forwardToGenerate($request, $export, $alias);
break;
default:
throw $this->createNotFoundException("The given step '$step' is invalid");
}
}
/**
*
* @param Request $request
* @param \Chill\MainBundle\Export\ExportInterface|\Chill\MainBundle\Export\DirectExportInterface $export
* @param string $alias
* @return Response
* @throws type
*/
protected function selectCentersStep(Request $request, $export, $alias)
{
/* @var $exportManager \Chill\MainBundle\Export\ExportManager */
$exportManager = $this->exportManager;
$form = $this->createCreateFormExport($alias, 'centers');
if ($request->getMethod() === 'POST') {
$form->handleRequest($request);
if ($form->isValid()) {
$this->logger->debug('form centers is valid', array(
'location' => __METHOD__));
$data = $form->getData();
// check ACL
if ($exportManager->isGrantedForElement($export, NULL,
$exportManager->getPickedCenters($data['centers'])) === FALSE) {
throw $this->createAccessDeniedException('you do not have '
. 'access to this export for those centers');
}
$this->session->set('centers_step_raw',
$request->request->all());
$this->session->set('centers_step', $data);
return $this->redirectToRoute('chill_main_export_new', array(
'step' => $this->getNextStep('centers', $export),
'alias' => $alias
));
}
}
return $this->render('@ChillMain/Export/new_centers_step.html.twig',
array(
'form' => $form->createView(),
'export' => $export
));
}
/**
* Render the export form
*
* When the method is POST, the form is stored if valid, and a redirection
* is done to next step.
*
* @param string $alias
* @param \Chill\MainBundle\Export\ExportInterface|\Chill\MainBundle\Export\DirectExportInterface $export
* @return \Symfony\Component\HttpFoundation\Response
*/
protected function exportFormStep(Request $request, $export, $alias)
{
$exportManager = $this->exportManager;
// check we have data from the previous step (export step)
$data = $this->session->get('centers_step', null);
if ($data === null) {
return $this->redirectToRoute('chill_main_export_new', array(
'step' => $this->getNextStep('export', $export, true),
'alias' => $alias
));
}
$export = $exportManager->getExport($alias);
$form = $this->createCreateFormExport($alias, 'export', $data);
if ($request->getMethod() === 'POST') {
$form->handleRequest($request);
if ($form->isValid()) {
$this->logger->debug('form export is valid', array(
'location' => __METHOD__));
// store data for reusing in next steps
$data = $form->getData();
$this->session->set('export_step_raw',
$request->request->all());
$this->session->set('export_step', $data);
//redirect to next step
return $this->redirect(
$this->generateUrl('chill_main_export_new', array(
'step' => $this->getNextStep('export', $export),
'alias' => $alias
)));
} else {
$this->logger->debug('form export is invalid', array(
'location' => __METHOD__));
}
}
return $this->render('@ChillMain/Export/new.html.twig', array(
'form' => $form->createView(),
'export_alias' => $alias,
'export' => $export
));
}
/**
* create a form to show on different steps.
*
* @param string $alias
* @param string $step, can either be 'export', 'formatter', 'generate_export' or 'generate_formatter' (last two are used by generate action)
* @param array $data the data from previous step. Required for steps 'formatter' and 'generate_formatter'
* @return \Symfony\Component\Form\Form
*/
protected function createCreateFormExport($alias, $step, $data = array())
{
/* @var $exportManager \Chill\MainBundle\Export\ExportManager */
$exportManager = $this->exportManager;
$isGenerate = strpos($step, 'generate_') === 0;
$builder = $this->formFactory
->createNamedBuilder(null, FormType::class, array(), array(
'method' => $isGenerate ? 'GET' : 'POST',
'csrf_protection' => $isGenerate ? false : true,
));
if ($step === 'centers' or $step === 'generate_centers') {
$builder->add('centers', PickCenterType::class, array(
'export_alias' => $alias
));
}
if ($step === 'export' or $step === 'generate_export') {
$builder->add('export', ExportType::class, array(
'export_alias' => $alias,
'picked_centers' => $exportManager->getPickedCenters($data['centers'])
));
}
if ($step === 'formatter' or $step === 'generate_formatter') {
$builder->add('formatter', FormatterType::class, array(
'formatter_alias' => $exportManager
->getFormatterAlias($data['export']),
'export_alias' => $alias,
'aggregator_aliases' => $exportManager
->getUsedAggregatorsAliases($data['export'])
));
}
$builder->add('submit', SubmitType::class, array(
'label' => 'Generate'
));
return $builder->getForm();
}
/**
* get the next step. If $reverse === true, the previous step is returned.
*
* This method provides a centralized way of handling next/previous step.
*
* @param string $step the current step
* @param \Chill\MainBundle\Export\ExportInterface|\Chill\MainBundle\Export\DirectExportInterface $export
* @param boolean $reverse set to true to get the previous step
* @return string the next/current step
* @throws \LogicException if there is no step before or after the given step
*/
private function getNextStep($step, $export, $reverse = false)
{
switch($step) {
case 'centers':
if ($reverse !== false) {
throw new \LogicException("there is no step before 'export'");
}
return 'export';
case 'export':
if ($export instanceof \Chill\MainBundle\Export\ExportInterface) {
return $reverse ? 'centers' : 'formatter';
} elseif ($export instanceof \Chill\MainBundle\Export\DirectExportInterface) {
return $reverse ? 'centers' : 'generate';
}
case 'formatter' :
return $reverse ? 'export' : 'generate';
case 'generate' :
if ($reverse === false) {
throw new \LogicException("there is no step after 'generate'");
}
return 'formatter';
default:
throw new \LogicException("the step $step is not defined.");
}
}
/**
* Render the form for formatter.
*
* If the form is posted and valid, store the data in session and
* redirect to the next step.
*
* @param Request $request
* @param \Chill\MainBundle\Export\ExportInterface|\Chill\MainBundle\Export\DirectExportInterface $export
* @param string $alias
* @return \Symfony\Component\HttpFoundation\Response
*/
protected function formatterFormStep(Request $request, $export, $alias)
{
// check we have data from the previous step (export step)
$data = $this->session->get('export_step', null);
if ($data === null) {
return $this->redirectToRoute('chill_main_export_new', array(
'step' => $this->getNextStep('formatter', $export, true),
'alias' => $alias
));
}
$form = $this->createCreateFormExport($alias, 'formatter', $data);
if ($request->getMethod() === 'POST') {
$form->handleRequest($request);
if ($form->isValid()) {
$dataFormatter = $form->getData();
$this->session->set('formatter_step', $dataFormatter);
$this->session->set('formatter_step_raw',
$request->request->all());
//redirect to next step
return $this->redirect($this->generateUrl('chill_main_export_new',
array(
'alias' => $alias,
'step' => $this->getNextStep('formatter', $export)
)));
}
}
return $this->render('@ChillMain/Export/new_formatter_step.html.twig',
array(
'form' => $form->createView(),
'export' => $export
));
}
/**
* Gather data stored in session from previous steps, store it inside redis
* and redirect to the `generate` action.
*
* The data from previous steps is removed from session.
*
* @param Request $request
* @param \Chill\MainBundle\Export\ExportInterface|\Chill\MainBundle\Export\DirectExportInterface $export
* @param string $alias
* @return \Symfony\Component\HttpFoundation\RedirectResponse
*/
protected function forwardToGenerate(Request $request, $export, $alias)
{
$dataCenters = $this->session->get('centers_step_raw', null);
$dataFormatter = $this->session->get('formatter_step_raw', null);
$dataExport = $this->session->get('export_step_raw', null);
if ($dataFormatter === NULL and $export instanceof \Chill\MainBundle\Export\ExportInterface) {
return $this->redirectToRoute('chill_main_export_new', array(
'alias' => $alias, 'step' => $this->getNextStep('generate', $export, true)
));
}
$parameters = [
'formatter' => $dataFormatter ?? [],
'export' => $dataExport ?? [],
'centers' => $dataCenters ?? [],
'alias' => $alias
];
unset($parameters['_token']);
$key = md5(uniqid(rand(), false));
$this->redis->setEx($key, 3600, \serialize($parameters));
// remove data from session
$this->session->remove('export_step_raw');
$this->session->remove('export_step');
$this->session->remove('formatter_step_raw');
$this->session->remove('formatter_step');
return $this->redirectToRoute('chill_main_export_download', [ 'key' => $key, 'alias' => $alias ]);
}
/**
* Generate a report.
*
* This action must work with GET queries.
*
* @param Request $request
* @param string $alias
* @return \Symfony\Component\HttpFoundation\Response
*/
public function generateAction(Request $request, $alias)
{
/* @var $exportManager \Chill\MainBundle\Export\ExportManager */
$exportManager = $this->exportManager;
$key = $request->query->get('key', null);
list($dataCenters, $dataExport, $dataFormatter) = $this->rebuildData($key);
$r = $exportManager->generate(
$alias,
$dataCenters['centers'],
$dataExport['export'],
$dataFormatter !== NULL ? $dataFormatter['formatter'] : []
);
return $r;
}
protected function rebuildData($key)
{
if ($key === NULL) {
throw $this->createNotFoundException("key does not exists");
}
if ($this->redis->exists($key) !== 1) {
$this->addFlash('error', $this->translator->trans("This report is not available any more"));
throw $this->createNotFoundException("key does not exists");
}
$serialized = $this->redis->get($key);
if ($serialized === false) {
throw new \LogicException("the key could not be reached from redis");
}
$rawData = \unserialize($serialized);
$alias = $rawData['alias'];
$formCenters = $this->createCreateFormExport($alias, 'generate_centers');
$formCenters->submit($rawData['centers']);
$dataCenters = $formCenters->getData();
$formExport = $this->createCreateFormExport($alias, 'generate_export', $dataCenters);
$formExport->submit($rawData['export']);
$dataExport = $formExport->getData();
if (count($rawData['formatter']) > 0) {
$formFormatter = $this->createCreateFormExport($alias, 'generate_formatter',
$dataExport);
$formFormatter->submit($rawData['formatter']);
$dataFormatter = $formFormatter->getData();
}
return [$dataCenters, $dataExport, $dataFormatter ?? null];
}
public function downloadResultAction(Request $request, $alias)
{
/* @var $exportManager \Chill\MainBundle\Export\ExportManager */
$exportManager = $this->exportManager;
$key = $request->query->get('key', null);
list($dataCenters, $dataExport, $dataFormatter) = $this->rebuildData($key);
$formatterAlias = $exportManager->getFormatterAlias($dataExport['export']);
if ($formatterAlias !== null) {
$formater = $exportManager->getFormatter($formatterAlias);
} else {
$formater = null;
}
$viewVariables = [
'alias' => $alias,
'export' => $exportManager->getExport($alias)
];
if ($formater instanceof \Chill\MainBundle\Export\Formatter\CSVListFormatter) {
// due to a bug in php, we add the mime type in the download view
$viewVariables['mime_type'] = 'text/csv';
}
return $this->render("@ChillMain/Export/download.html.twig", $viewVariables);
}
}

View File

@@ -0,0 +1,48 @@
<?php
namespace Chill\MainBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
/**
* Class LoginController
*
* @package Chill\MainBundle\Controller
*/
class LoginController extends AbstractController
{
/**
*
* @var AuthenticationUtils
*/
protected $helper;
public function __construct(AuthenticationUtils $helper)
{
$this->helper = $helper;
}
/**
* Show a login form
*
* @param Request $request
* @return Response
*/
public function loginAction(Request $request)
{
return $this->render('@ChillMain/Login/login.html.twig', array(
'last_username' => $this->helper->getLastUsername(),
'error' => $this->helper->getLastAuthenticationError()
));
}
public function LoginCheckAction(Request $request)
{
}
}

View File

@@ -0,0 +1,23 @@
<?php
namespace Chill\MainBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
/**
* Class MenuController
*
* @package Chill\MainBundle\Controller
*/
class MenuController extends AbstractController
{
public function writeMenuAction($menu, $layout, $activeRouteKey = null, array $args = array() )
{
return $this->render($layout, array(
'menu_composer' => $this->get('chill.main.menu_composer'),
'menu' => $menu,
'args' => $args,
'activeRouteKey' => $activeRouteKey
));
}
}

View File

@@ -0,0 +1,336 @@
<?php
namespace Chill\MainBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Chill\MainBundle\Form\UserPasswordType;
use Chill\MainBundle\Entity\User;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Translation\TranslatorInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Validator\Constraints\Callback;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Chill\MainBundle\Security\PasswordRecover\RecoverPasswordHelper;
use Symfony\Component\HttpFoundation\Response;
use Chill\MainBundle\Security\PasswordRecover\TokenManager;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Chill\MainBundle\Security\PasswordRecover\PasswordRecoverEvent;
use Chill\MainBundle\Security\PasswordRecover\PasswordRecoverVoter;
/**
* Class PasswordController
*
* @package Chill\MainBundle\Controller
*/
class PasswordController extends AbstractController
{
/**
* @var UserPasswordEncoderInterface
*/
protected $passwordEncoder;
/**
* @var TranslatorInterface
*/
protected $translator;
/**
* @var LoggerInterface
*/
protected $chillLogger;
/**
* @var RecoverPasswordHelper
*/
protected $recoverPasswordHelper;
/**
* @var TokenManager
*/
protected $tokenManager;
/**
* @var EventDispatcherInterface
*/
protected $eventDispatcher;
/**
* PasswordController constructor.
*
* @param LoggerInterface $chillLogger
* @param UserPasswordEncoderInterface $passwordEncoder
* @param RecoverPasswordHelper $recoverPasswordHelper
* @param TokenManager $tokenManager
* @param TranslatorInterface $translator
* @param EventDispatcherInterface $eventDispatcher
*/
public function __construct(
LoggerInterface $chillLogger,
UserPasswordEncoderInterface $passwordEncoder,
RecoverPasswordHelper $recoverPasswordHelper,
TokenManager $tokenManager,
TranslatorInterface $translator,
EventDispatcherInterface $eventDispatcher
) {
$this->chillLogger = $chillLogger;
$this->passwordEncoder = $passwordEncoder;
$this->translator = $translator;
$this->tokenManager = $tokenManager;
$this->recoverPasswordHelper = $recoverPasswordHelper;
$this->eventDispatcher = $eventDispatcher;
}
/**
* @param Request $request
* @return Response
*/
public function UserPasswordAction(Request $request)
{
// get authentified user
$user = $this->getUser();
// create a form for password_encoder
$form = $this->passwordForm($user);
// process the form
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$password = $form->get('new_password')->getData();
// logging for prod
$this
->chillLogger
->notice(
'update password for an user',
array(
'method' => $request->getMethod(),
'user' => $user->getUsername()
)
);
$user->setPassword($this->passwordEncoder->encodePassword($user, $password));
$em = $this->getDoctrine()->getManager();
$em->flush();
$this->addFlash('success', $this->translator->trans('Password successfully updated!'));
return $this->redirectToRoute('change_my_password');
}
// render into a template
return $this->render('@ChillMain/Password/password.html.twig', array(
'form' => $form->createView()
));
}
/**
* @param User $user
* @return \Symfony\Component\Form\Form
*/
private function passwordForm(User $user)
{
return $this
->createForm(
UserPasswordType::class,
[],
[ 'user' => $user ]
)
->add('submit', SubmitType::class, array('label' => 'Change password'))
;
}
/**
* @param Request $request
* @return \Symfony\Component\HttpFoundation\RedirectResponse|Response
*/
public function recoverAction(Request $request)
{
if (FALSE === $this->isGranted(PasswordRecoverVoter::ASK_TOKEN)) {
return (new Response($this->translator->trans("You are not allowed "
. "to try to recover password, due to mitigating possible "
. "attack. Try to contact your system administrator"), Response::HTTP_FORBIDDEN));
}
$query = $request->query;
$username = $query->get(TokenManager::USERNAME_CANONICAL);
$hash = $query->getAlnum(TokenManager::HASH);
$token = $query->getAlnum(TokenManager::TOKEN);
$timestamp = $query->getInt(TokenManager::TIMESTAMP);
$user = $this->getDoctrine()->getRepository(User::class)
->findOneByUsernameCanonical($username);
if (NULL === $user) {
$this->eventDispatcher->dispatch(PasswordRecoverEvent::INVALID_TOKEN,
new PasswordRecoverEvent($token, null, $request->getClientIp()));
throw $this->createNotFoundException(sprintf('User %s not found', $username));
}
if (TRUE !== $this->tokenManager->verify($hash, $token, $user, $timestamp)) {
$this->eventDispatcher->dispatch(PasswordRecoverEvent::INVALID_TOKEN,
new PasswordRecoverEvent($token, $user, $request->getClientIp()));
return new Response("Invalid token", Response::HTTP_FORBIDDEN);
}
$form = $this->passwordForm($user);
$form->remove('actual_password');
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$password = $form->get('new_password')->getData();
$user->setPassword($this->passwordEncoder->encodePassword($user, $password));
// logging for prod
$this
->chillLogger
->notice(
'setting new password for user',
array(
'user' => $user->getUsername()
)
);
$this->getDoctrine()->getManager()->flush();
return $this->redirectToRoute('password_request_recover_changed');
}
return $this->render('@ChillMain/Password/recover_password_form.html.twig', [
'form' => $form->createView()
]);
}
/**
* @return Response
*/
public function changeConfirmedAction()
{
return $this->render('@ChillMain/Password/recover_password_changed.html.twig');
}
/**
* @param Request $request
* @return \Symfony\Component\HttpFoundation\RedirectResponse|Response
* @throws \Doctrine\ORM\NoResultException
* @throws \Doctrine\ORM\NonUniqueResultException
*/
public function requestRecoverAction(Request $request)
{
if (FALSE === $this->isGranted(PasswordRecoverVoter::ASK_TOKEN)) {
return (new Response($this->translator->trans("You are not allowed "
. "to try to recover password, due to mitigating possible "
. "attack. Try to contact your system administrator"), Response::HTTP_FORBIDDEN));
}
$form = $this->requestRecoverForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
/* @var $qb \Doctrine\ORM\QueryBuilder */
$qb = $this->getDoctrine()->getManager()
->createQueryBuilder();
$qb->select('u')
->from(User::class, 'u')
->where($qb->expr()->eq('u.usernameCanonical', 'UNACCENT(LOWER(:pattern))'))
->orWhere($qb->expr()->eq('u.emailCanonical', 'UNACCENT(LOWER(:pattern))' ))
->setParameter('pattern', $form->get('username_or_email')->getData())
;
$user = $qb->getQuery()->getSingleResult();
if (empty($user->getEmail())) {
$this->addFlash('error', $this->translator->trans('This account does not have an email address. '
. 'Please ask your administrator to renew your password.'));
} else {
if (FALSE === $this->isGranted(PasswordRecoverVoter::ASK_TOKEN, $user)) {
return (new Response($this->translator->trans("You are not allowed "
. "to try to recover password, due to mitigating possible "
. "attack. Try to contact your system administrator"), Response::HTTP_FORBIDDEN));
}
$this->recoverPasswordHelper->sendRecoverEmail($user,
(new \DateTimeImmutable('now'))->add(new \DateInterval('PT30M')));
// logging for prod
$this
->chillLogger
->notice(
'Sending an email for password recovering',
array(
'user' => $user->getUsername()
)
);
$this->eventDispatcher->dispatch(
PasswordRecoverEvent::ASK_TOKEN_SUCCESS,
new PasswordRecoverEvent(null, $user, $request->getClientIp())
);
return $this->redirectToRoute('password_request_recover_confirm');
}
} elseif ($form->isSubmitted() && FALSE === $form->isValid()) {
$this->eventDispatcher->dispatch(
PasswordRecoverEvent::ASK_TOKEN_INVALID_FORM,
new PasswordRecoverEvent(null, null, $request->getClientIp())
);
}
return $this->render('@ChillMain/Password/request_recover_password.html.twig', [
'form' => $form->createView()
]);
}
/**
* @return Response
*/
public function requestRecoverConfirmAction()
{
return $this->render('@ChillMain/Password/request_recover_password_confirm.html.twig');
}
/**
* @return \Symfony\Component\Form\FormInterface
*/
protected function requestRecoverForm()
{
$builder = $this->createFormBuilder();
$builder
->add('username_or_email', TextType::class, [
'label' => 'Username or email',
'constraints' => [
new Callback([
'callback' => function($pattern, ExecutionContextInterface $context, $payload) {
$qb = $this->getDoctrine()->getManager()
->createQueryBuilder();
$qb->select('COUNT(u)')
->from(User::class, 'u')
->where($qb->expr()->eq('u.usernameCanonical', 'UNACCENT(LOWER(:pattern))'))
->orWhere($qb->expr()->eq('u.emailCanonical', 'UNACCENT(LOWER(:pattern))' ))
->setParameter('pattern', $pattern)
;
if ((int) $qb->getQuery()->getSingleScalarResult() !== 1) {
$context->addViolation('This username or email does not exists');
}
}
])
]
])
->add('submit', SubmitType::class, [
'label' => 'Request recover'
]);
return $builder->getForm();
}
}

View File

@@ -0,0 +1,550 @@
<?php
namespace Chill\MainBundle\Controller;
use Chill\MainBundle\Security\RoleProvider;
use Chill\MainBundle\Templating\TranslatableStringHelper;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Chill\MainBundle\Entity\RoleScope;
use Chill\MainBundle\Entity\PermissionsGroup;
use Chill\MainBundle\Form\PermissionsGroupType;
use Symfony\Component\Security\Core\Role\Role;
use Symfony\Component\Security\Core\Role\RoleHierarchy;
use Chill\MainBundle\Entity\Scope;
use Chill\MainBundle\Form\Type\ComposedRoleScopeType;
use Symfony\Contracts\Translation\TranslatorInterface;
/**
* Class PermissionsGroupController
*
* @package Chill\MainBundle\Controller
*/
class PermissionsGroupController extends AbstractController
{
/**
* @var TranslatableStringHelper
*/
private $translatableStringHelper;
/**
* @var RoleProvider $roleProvider
*/
private $roleProvider;
/**
* @var RoleHierarchy $roleHierarchy
*/
private $roleHierarchy;
/**
* @var TranslatorInterface
*/
private $translator;
/**
* PermissionsGroupController constructor.
*
* @param TranslatableStringHelper $translatableStringHelper
* @param RoleProvider $roleProvider
* @param RoleHierarchy $roleHierarchy
* @param TranslatorInterface $translator
*/
public function __construct(
TranslatableStringHelper $translatableStringHelper,
RoleProvider $roleProvider,
RoleHierarchy $roleHierarchy,
TranslatorInterface $translator
)
{
$this->translatableStringHelper = $translatableStringHelper;
$this->roleProvider = $roleProvider;
$this->roleHierarchy = $roleHierarchy;
$this->translator = $translator;
}
/**
* Lists all PermissionsGroup entities.
*
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('ChillMainBundle:PermissionsGroup')->findAll();
return $this->render('@ChillMain/PermissionsGroup/index.html.twig', array(
'entities' => $entities,
));
}
/**
* Creates a new PermissionsGroup entity.
*
*/
public function createAction(Request $request)
{
$permissionsGroup = new PermissionsGroup();
$form = $this->createCreateForm($permissionsGroup);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($permissionsGroup);
$em->flush();
return $this->redirect($this->generateUrl('admin_permissionsgroup_edit',
array('id' => $permissionsGroup->getId())));
}
return $this->render('@ChillMain/PermissionsGroup/new.html.twig', array(
'entity' => $permissionsGroup,
'form' => $form->createView(),
));
}
/**
* Creates a form to create a PermissionsGroup entity.
*
* @param PermissionsGroup $permissionsGroup The entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createCreateForm(PermissionsGroup $permissionsGroup)
{
$form = $this->createForm(PermissionsGroupType::class, $permissionsGroup, array(
'action' => $this->generateUrl('admin_permissionsgroup_create'),
'method' => 'POST',
));
$form->add('submit', SubmitType::class, array('label' => 'Create'));
return $form;
}
/**
* Displays a form to create a new PermissionsGroup entity.
*
*/
public function newAction()
{
$permissionsGroup = new PermissionsGroup();
$form = $this->createCreateForm($permissionsGroup);
return $this->render('@ChillMain/PermissionsGroup/new.html.twig', array(
'entity' => $permissionsGroup,
'form' => $form->createView(),
));
}
/**
* Finds and displays a PermissionsGroup entity.
*
*/
public function showAction($id)
{
$em = $this->getDoctrine()->getManager();
$permissionsGroup = $em->getRepository('ChillMainBundle:PermissionsGroup')->find($id);
if (!$permissionsGroup) {
throw $this->createNotFoundException('Unable to find PermissionsGroup entity.');
}
$translatableStringHelper = $this->translatableStringHelper;
$roleScopes = $permissionsGroup->getRoleScopes()->toArray();
// sort $roleScopes by name
usort($roleScopes,
function(RoleScope $a, RoleScope $b) use ($translatableStringHelper) {
if ($a->getScope() === NULL) {
return 1;
}
if ($b->getScope() === NULL) {
return +1;
}
return strcmp(
$translatableStringHelper->localize($a->getScope()->getName()),
$translatableStringHelper->localize($b->getScope()->getName())
);
});
// sort role scope by title
$roleProvider = $this->roleProvider;
$roleScopesSorted = array();
foreach($roleScopes as $roleScope) {
/* @var $roleScope RoleScope */
$title = $roleProvider->getRoleTitle($roleScope->getRole());
$roleScopesSorted[$title][] = $roleScope;
}
ksort($roleScopesSorted);
return $this->render('@ChillMain/PermissionsGroup/show.html.twig', array(
'entity' => $permissionsGroup,
'role_scopes_sorted' => $roleScopesSorted,
'expanded_roles' => $this->getExpandedRoles($roleScopes)
));
}
/**
* expand roleScopes to be easily shown in template
*
* @param array $roleScopes
* @return array
*/
private function getExpandedRoles(array $roleScopes)
{
$expandedRoles = array();
foreach ($roleScopes as $roleScope) {
if (!array_key_exists($roleScope->getRole(), $expandedRoles)) {
$expandedRoles[$roleScope->getRole()] =
array_map(
function(Role $role) {
return $role->getRole();
},
$this->roleHierarchy
->getReachableRoles(
array(new Role($roleScope->getRole()))
)
);
}
}
return $expandedRoles;
}
/**
* Displays a form to edit an existing PermissionsGroup entity.
*
*/
public function editAction($id)
{
$em = $this->getDoctrine()->getManager();
$permissionsGroup = $em->getRepository('ChillMainBundle:PermissionsGroup')->find($id);
if (!$permissionsGroup) {
throw $this->createNotFoundException('Unable to find PermissionsGroup entity.');
}
// create all the forms
$editForm = $this->createEditForm($permissionsGroup);
$deleteRoleScopesForm = array();
foreach ($permissionsGroup->getRoleScopes() as $roleScope) {
$deleteRoleScopesForm[$roleScope->getId()] = $this->createDeleteRoleScopeForm(
$permissionsGroup, $roleScope);
}
$addRoleScopesForm = $this->createAddRoleScopeForm($permissionsGroup);
// sort role scope by title
$roleProvider = $this->roleProvider;
$roleScopesSorted = array();
foreach($permissionsGroup->getRoleScopes()->toArray() as $roleScope) {
/* @var $roleScope RoleScope */
$title = $roleProvider->getRoleTitle($roleScope->getRole());
$roleScopesSorted[$title][] = $roleScope;
}
ksort($roleScopesSorted);
return $this->render('@ChillMain/PermissionsGroup/edit.html.twig', array(
'entity' => $permissionsGroup,
'role_scopes_sorted' => $roleScopesSorted,
'edit_form' => $editForm->createView(),
'expanded_roles' => $this->getExpandedRoles($permissionsGroup->getRoleScopes()->toArray()),
'delete_role_scopes_form' => array_map( function($form) {
return $form->createView();
}, $deleteRoleScopesForm),
'add_role_scopes_form' => $addRoleScopesForm->createView()
));
}
/**
* Creates a form to edit a PermissionsGroup entity.
*
* @param PermissionsGroup $permissionsGroup The entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createEditForm(PermissionsGroup $permissionsGroup)
{
$form = $this->createForm(PermissionsGroupType::class, $permissionsGroup, array(
'action' => $this->generateUrl('admin_permissionsgroup_update', array('id' => $permissionsGroup->getId())),
'method' => 'PUT',
));
$form->add('submit', SubmitType::class, array('label' => 'Update'));
return $form;
}
/**
* Edits an existing PermissionsGroup entity.
*
*/
public function updateAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$permissionsGroup = $em
->getRepository('ChillMainBundle:PermissionsGroup')
->find($id);
if (!$permissionsGroup) {
throw $this->createNotFoundException('Unable to find Permissions'
. 'Group entity.');
}
$editForm = $this->createEditForm($permissionsGroup);
$editForm->handleRequest($request);
if ($editForm->isValid()) {
$em->flush();
return $this->redirect($this->generateUrl('admin_permissionsgroup_edit', array('id' => $id)));
}
$deleteRoleScopesForm = array();
foreach ($permissionsGroup->getRoleScopes() as $roleScope) {
$deleteRoleScopesForm[$roleScope->getId()] = $this->createDeleteRoleScopeForm(
$permissionsGroup, $roleScope);
}
$addRoleScopesForm = $this->createAddRoleScopeForm($permissionsGroup);
// sort role scope by title
$roleProvider = $this->roleProvider;
$roleScopesSorted = array();
foreach($permissionsGroup->getRoleScopes()->toArray() as $roleScope) {
/* @var $roleScope RoleScope */
$title = $roleProvider->getRoleTitle($roleScope->getRole());
$roleScopesSorted[$title][] = $roleScope;
}
ksort($roleScopesSorted);
return $this->render('@ChillMain/PermissionsGroup/edit.html.twig', array(
'entity' => $permissionsGroup,
'role_scopes_sorted' => $roleScopesSorted,
'edit_form' => $editForm->createView(),
'expanded_roles' => $this->getExpandedRoles($permissionsGroup->getRoleScopes()->toArray()),
'delete_role_scopes_form' => array_map( function($form) {
return $form->createView();
}, $deleteRoleScopesForm),
'add_role_scopes_form' => $addRoleScopesForm->createView()
));
}
/**
* get a role scope by his parameters. The role scope is persisted if it
* doesn't exists in database.
*
* @param Scope $scope
* @param string $role
* @return RoleScope
*/
protected function getPersistentRoleScopeBy($role, Scope $scope = null)
{
$em = $this->getDoctrine()->getManager();
$roleScope = $em->getRepository('ChillMainBundle:RoleScope')
->findOneBy(array('role' => $role, 'scope' => $scope));
if ($roleScope === NULL) {
$roleScope = (new RoleScope())
->setRole($role)
->setScope($scope)
;
$em->persist($roleScope);
}
return $roleScope;
}
/**
* remove an association between permissionsGroup and roleScope
*
* @param int $pgid permissionsGroup id
* @param int $rsid roleScope id
* @return redirection to edit form
*/
public function deleteLinkRoleScopeAction($pgid, $rsid)
{
$em = $this->getDoctrine()->getManager();
$permissionsGroup = $em->getRepository('ChillMainBundle:PermissionsGroup')->find($pgid);
$roleScope = $em->getRepository('ChillMainBundle:RoleScope')->find($rsid);
if (!$permissionsGroup) {
throw $this->createNotFoundException('Unable to find PermissionsGroup entity.');
}
if (!$roleScope) {
throw $this->createNotFoundException('Unable to find RoleScope entity');
}
try {
$permissionsGroup->removeRoleScope($roleScope);
} catch (\RuntimeException $ex) {
$this->addFlash('notice',
$this->translator->trans("The role '%role%' and circle "
. "'%scope%' is not associated with this permission group", array(
'%role%' => $this->translator->trans($roleScope->getRole()),
'%scope%' => $this->translatableStringHelper
->localize($roleScope->getScope()->getName())
)));
return $this->redirect($this->generateUrl('admin_permissionsgroup_edit',
array('id' => $pgid)));
}
$em->flush();
if ($roleScope->getScope() !== NULL ) {
$this->addFlash('notice',
$this->translator->trans("The role '%role%' on circle "
. "'%scope%' has been removed", array(
'%role%' => $this->translator->trans($roleScope->getRole()),
'%scope%' => $this->translatableStringHelper
->localize($roleScope->getScope()->getName())
)));
} else {
$this->addFlash('notice',
$this->translator->trans("The role '%role%' has been removed", array(
'%role%' => $this->translator->trans($roleScope->getRole())
)));
}
return $this->redirect($this->generateUrl('admin_permissionsgroup_edit',
array('id' => $pgid)));
}
/**
*
* @param Request $request
* @param int $id
* @return Respon
* @throws type
*/
public function addLinkRoleScopeAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$permissionsGroup = $em->getRepository('ChillMainBundle:PermissionsGroup')->find($id);
if (!$permissionsGroup) {
throw $this->createNotFoundException('Unable to find PermissionsGroup entity.');
}
$form = $this->createAddRoleScopeForm($permissionsGroup);
$form->handleRequest($request);
if ($form->isValid()) {
$roleScope = $this->getPersistentRoleScopeBy(
$form['composed_role_scope']->getData()->getRole(),
$form['composed_role_scope']->getData()->getScope()
);
$permissionsGroup->addRoleScope($roleScope);
$violations = $this->get('validator')->validate($permissionsGroup);
if ($violations->count() === 0) {
$em->flush();
$this->addFlash('notice',
$this->translator->trans("The permissions have been added"));
return $this->redirect($this->generateUrl('admin_permissionsgroup_edit',
array('id' => $id)));
} else {
foreach($violations as $error) {
$this->addFlash('error', $error->getMessage());
}
}
} else {
foreach ($form->getErrors() as $error) {
$this->addFlash('error', $error->getMessage());
}
}
$editForm = $this->createEditForm($permissionsGroup);
$deleteRoleScopesForm = array();
foreach ($permissionsGroup->getRoleScopes() as $roleScope) {
$deleteRoleScopesForm[$roleScope->getId()] = $this->createDeleteRoleScopeForm(
$permissionsGroup, $roleScope);
}
$addRoleScopesForm = $this->createAddRoleScopeForm($permissionsGroup);
// sort role scope by title
$roleProvider = $this->roleProvider;
$roleScopesSorted = array();
foreach($permissionsGroup->getRoleScopes()->toArray() as $roleScope) {
/* @var $roleScope RoleScope */
$title = $roleProvider->getRoleTitle($roleScope->getRole());
$roleScopesSorted[$title][] = $roleScope;
}
ksort($roleScopesSorted);
return $this->render('@ChillMain/PermissionsGroup/edit.html.twig', array(
'entity' => $permissionsGroup,
'edit_form' => $editForm->createView(),
'role_scopes_sorted' => $roleScopesSorted,
'expanded_roles' => $this->getExpandedRoles($permissionsGroup->getRoleScopes()->toArray()),
'delete_role_scopes_form' => array_map( function($form) {
return $form->createView();
}, $deleteRoleScopesForm),
'add_role_scopes_form' => $addRoleScopesForm->createView()
));
}
/**
* Creates a form to delete a link to roleScope.
*
* @param mixed $permissionsGroup The entity id
*
* @return \Symfony\Component\Form\Form The form
*/
private function createDeleteRoleScopeForm(PermissionsGroup $permissionsGroup,
RoleScope $roleScope)
{
return $this->createFormBuilder()
->setAction($this->generateUrl('admin_permissionsgroup_delete_role_scope',
array('pgid' => $permissionsGroup->getId(), 'rsid' => $roleScope->getId())))
->setMethod('DELETE')
->add('submit', SubmitType::class, array('label' => 'Delete'))
->getForm()
;
}
/**
* creates a form to add a role scope to permissionsgroup
*
* @param PermissionsGroup $permissionsGroup
* @return \Symfony\Component\Form\Form The form
*/
private function createAddRoleScopeForm(PermissionsGroup $permissionsGroup)
{
return $this->createFormBuilder()
->setAction($this->generateUrl('admin_permissionsgroup_add_role_scope',
array('id' => $permissionsGroup->getId())))
->setMethod('PUT')
->add('composed_role_scope', ComposedRoleScopeType::class)
->add('submit', SubmitType::class, array('label' => 'Add permission'))
->getForm()
;
}
}

View File

@@ -0,0 +1,90 @@
<?php
/*
* Chill is a software for social workers
*
* Copyright (C) 2018, Champs Libres Cooperative SCRLFS, <http://www.champs-libres.coop>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Chill\MainBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Chill\MainBundle\Entity\PostalCode;
use Symfony\Component\HttpFoundation\JsonResponse;
use Chill\MainBundle\Templating\TranslatableStringHelper;
use Doctrine\ORM\Query;
/**
* Class PostalCodeController
*
* @package Chill\MainBundle\Controller
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/
class PostalCodeController extends AbstractController
{
/**
*
* @var TranslatableStringHelper
*/
protected $translatableStringHelper;
public function __construct(TranslatableStringHelper $translatableStringHelper)
{
$this->translatableStringHelper = $translatableStringHelper;
}
/**
*
* @Route(
* "{_locale}/postalcode/search"
* )
* @param Request $request
* @return JsonResponse
*/
public function searchAction(Request $request)
{
$pattern = $request->query->getAlnum('q', '');
if (empty($pattern)) {
return new JsonResponse(["results" => [], "pagination" => [ "more" => false]]);
}
$query = $this->getDoctrine()->getManager()
->createQuery(sprintf(
"SELECT p.id AS id, p.name AS name, p.code AS code, "
. "country.name AS country_name, "
. "country.countryCode AS country_code "
. "FROM %s p "
. "JOIN p.country country "
. "WHERE LOWER(p.name) LIKE LOWER(:pattern) OR LOWER(p.code) LIKE LOWER(:pattern) "
. "ORDER BY code"
, PostalCode::class)
)
->setParameter('pattern', '%'.$pattern.'%')
->setMaxResults(30)
;
$results = \array_map(function($row) {
$row['country_name'] = $this->translatableStringHelper->localize($row['country_name']);
$row['text'] = $row['code']." ".$row["name"]." (".$row['country_name'].")";
return $row;
}, $query->getResult(Query::HYDRATE_ARRAY));
return new JsonResponse([ 'results' => $results, "pagination" => [ "more" => false ] ]);
}
}

View File

@@ -0,0 +1,178 @@
<?php
namespace Chill\MainBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Chill\MainBundle\Entity\Scope;
use Chill\MainBundle\Form\ScopeType;
/**
* Class ScopeController
*
* @package Chill\MainBundle\Controller
*/
class ScopeController extends AbstractController
{
/**
* Lists all Scope entities.
*
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('ChillMainBundle:Scope')->findAll();
return $this->render('@ChillMain/Scope/index.html.twig', array(
'entities' => $entities,
));
}
/**
* Creates a new Scope entity.
*
*/
public function createAction(Request $request)
{
$scope = new Scope();
$form = $this->createCreateForm($scope);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($scope);
$em->flush();
return $this->redirect($this->generateUrl('admin_scope_show', array('id' => $scope->getId())));
}
return $this->render('@ChillMain/Scope/new.html.twig', array(
'entity' => $scope,
'form' => $form->createView(),
));
}
/**
* Creates a form to create a Scope entity.
*
* @param Scope $scope The entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createCreateForm(Scope $scope)
{
$form = $this->createForm(ScopeType::class, $scope, array(
'action' => $this->generateUrl('admin_scope_create'),
'method' => 'POST',
));
$form->add('submit', SubmitType::class, array('label' => 'Create'));
return $form;
}
/**
* Displays a form to create a new Scope entity.
*
*/
public function newAction()
{
$scope = new Scope();
$form = $this->createCreateForm($scope);
return $this->render('@ChillMain/Scope/new.html.twig', array(
'entity' => $scope,
'form' => $form->createView(),
));
}
/**
* Finds and displays a Scope entity.
*
*/
public function showAction($id)
{
$em = $this->getDoctrine()->getManager();
$scope = $em->getRepository('ChillMainBundle:Scope')->find($id);
if (!$scope) {
throw $this->createNotFoundException('Unable to find Scope entity.');
}
return $this->render('@ChillMain/Scope/show.html.twig', array(
'entity' => $scope
));
}
/**
* Displays a form to edit an existing Scope entity.
*
*/
public function editAction($id)
{
$em = $this->getDoctrine()->getManager();
$scope = $em->getRepository('ChillMainBundle:Scope')->find($id);
if (!$scope) {
throw $this->createNotFoundException('Unable to find Scope entity.');
}
$editForm = $this->createEditForm($scope);
return $this->render('@ChillMain/Scope/edit.html.twig', array(
'entity' => $scope,
'edit_form' => $editForm->createView(),
));
}
/**
* Creates a form to edit a Scope entity.
*
* @param Scope $scope The entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createEditForm(Scope $scope)
{
$form = $this->createForm(ScopeType::class, $scope, array(
'action' => $this->generateUrl('admin_scope_update', array('id' => $scope->getId())),
'method' => 'PUT',
));
$form->add('submit', SubmitType::class, array('label' => 'Update'));
return $form;
}
/**
* Edits an existing Scope entity.
*
*/
public function updateAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$scope = $em->getRepository('ChillMainBundle:Scope')->find($id);
if (!$scope) {
throw $this->createNotFoundException('Unable to find Scope entity.');
}
$editForm = $this->createEditForm($scope);
$editForm->handleRequest($request);
if ($editForm->isValid()) {
$em->flush();
return $this->redirect($this->generateUrl('admin_scope_edit', array('id' => $id)));
}
return $this->render('@ChillMain/Scope/edit.html.twig', array(
'entity' => $scope,
'edit_form' => $editForm->createView()
));
}
}

View File

@@ -0,0 +1,240 @@
<?php
/*
* Chill is a software for social workers
*
* Copyright (C) 2014, Champs Libres Cooperative SCRLFS, <http://www.champs-libres.coop>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Chill\MainBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Chill\MainBundle\Search\UnknowSearchDomainException;
use Chill\MainBundle\Search\UnknowSearchNameException;
use Chill\MainBundle\Search\ParsingException;
use Chill\MainBundle\Search\SearchInterface;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\HttpFoundation\JsonResponse;
use Chill\MainBundle\Search\SearchProvider;
use Symfony\Contracts\Translation\TranslatorInterface;
use Chill\MainBundle\Pagination\PaginatorFactory;
/**
* Class SearchController
*
* @package Chill\MainBundle\Controller
*/
class SearchController extends AbstractController
{
/**
*
* @var SearchProvider
*/
protected $searchProvider;
/**
*
* @var TranslatorInterface
*/
protected $translator;
/**
*
* @var PaginatorFactory
*/
protected $paginatorFactory;
function __construct(
SearchProvider $searchProvider,
TranslatorInterface $translator,
PaginatorFactory $paginatorFactory
) {
$this->searchProvider = $searchProvider;
$this->translator = $translator;
$this->paginatorFactory = $paginatorFactory;
}
public function searchAction(Request $request, $_format)
{
$pattern = $request->query->get('q', '');
if ($pattern === ''){
switch($_format) {
case 'html':
return $this->render('@ChillMain/Search/error.html.twig',
array(
'message' => $this->translator->trans("Your search is empty. "
. "Please provide search terms."),
'pattern' => $pattern
));
case 'json':
return new JsonResponse([
'results' => [],
'pagination' => [ 'more' => false ]
]);
}
}
$name = $request->query->get('name', NULL);
try {
if ($name === NULL) {
if ($_format === 'json') {
return new JsonResponse('Currently, we still do not aggregate results '
. 'from different providers', JsonResponse::HTTP_BAD_REQUEST);
}
// no specific search selected. Rendering result in "preview" mode
$results = $this->searchProvider
->getSearchResults(
$pattern,
0,
5,
array(SearchInterface::SEARCH_PREVIEW_OPTION => true)
);
} else {
// we want search on a specific search provider. Display full results.
$results = [$this->searchProvider
->getResultByName(
$pattern,
$name,
$this->paginatorFactory->getCurrentPageFirstItemNumber(),
$this->paginatorFactory->getCurrentItemsPerPage(),
array(
SearchInterface::SEARCH_PREVIEW_OPTION => false,
SearchInterface::REQUEST_QUERY_PARAMETERS => $request
->get(SearchInterface::REQUEST_QUERY_KEY_ADD_PARAMETERS, [])
),
$_format
)];
if ($_format === 'json') {
return new JsonResponse(\reset($results));
}
}
} catch (UnknowSearchDomainException $ex) {
return $this->render('@ChillMain/Search/error.html.twig',
array(
"message" => $this->translator->trans("The domain %domain% "
. "is unknow. Please check your search.", array('%domain%' => $ex->getDomain())),
'pattern' => $pattern
));
} catch (UnknowSearchNameException $ex) {
throw $this->createNotFoundException("The name ".$ex->getName()." is not found");
} catch (ParsingException $ex) {
return $this->render('@ChillMain/Search/error.html.twig',
array(
"message" => $this->translator->trans('Invalid terms').
": ".$this->translator->trans($ex->getMessage()),
'pattern' => $pattern
));
}
return $this->render('@ChillMain/Search/list.html.twig',
array('results' => $results, 'pattern' => $pattern)
);
}
public function advancedSearchListAction(Request $request)
{
/* @var $variable Chill\MainBundle\Search\SearchProvider */
$searchProvider = $this->searchProvider;
$advancedSearchProviders = $searchProvider
->getHasAdvancedFormSearchServices();
if(\count($advancedSearchProviders) === 1) {
\reset($advancedSearchProviders);
return $this->redirectToRoute('chill_main_advanced_search', [
'name' => \key($advancedSearchProviders)
]);
}
return $this->render('@ChillMain/Search/choose_list.html.twig');
}
public function advancedSearchAction($name, Request $request)
{
try {
/* @var $variable Chill\MainBundle\Search\SearchProvider */
$searchProvider = $this->searchProvider;
/* @var $variable Chill\MainBundle\Search\HasAdvancedSearchFormInterface */
$search = $this->searchProvider
->getHasAdvancedFormByName($name);
} catch (\Chill\MainBundle\Search\UnknowSearchNameException $e) {
throw $this->createNotFoundException("no advanced search for "
. "$name");
}
if ($request->query->has('q')) {
$data = $search->convertTermsToFormData($searchProvider->parse(
$request->query->get('q')));
}
$form = $this->createAdvancedSearchForm($name, $data ?? []);
if ($request->isMethod(Request::METHOD_POST)) {
$form->handleRequest($request);
if ($form->isValid()) {
$pattern = $this->searchProvider
->getHasAdvancedFormByName($name)
->convertFormDataToQuery($form->getData());
return $this->redirectToRoute('chill_main_search', [
'q' => $pattern, 'name' => $name
]);
}
}
return $this->render('@ChillMain/Search/advanced_search.html.twig',
[
'form' => $form->createView(),
'name' => $name,
'title' => $search->getAdvancedSearchTitle()
]);
}
protected function createAdvancedSearchForm($name, array $data = [])
{
$builder = $this
->get('form.factory')
->createNamedBuilder(
null,
FormType::class,
$data,
[ 'method' => Request::METHOD_POST ]
);
$this->searchProvider
->getHasAdvancedFormByName($name)
->buildForm($builder)
;
$builder->add('submit', SubmitType::class, [
'label' => 'Search'
]);
return $builder->getForm();
}
}

View File

@@ -0,0 +1,40 @@
<?php
/*
* Copyright (C) 2018 Champs Libres Cooperative <info@champs-libres.coop>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Chill\MainBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Chill\MainBundle\Templating\UI\CountNotificationUser;
/**
* Class UIController
*
* @package Chill\MainBundle\Controller
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/
class UIController extends AbstractController
{
public function showNotificationUserCounterAction(
CountNotificationUser $counter
) {
$nb = $counter->getSumNotification($this->getUser());
return $this->render('@ChillMain/UI/notification_user_counter.html.twig', [
'nb' => $nb
]);
}
}

View File

@@ -0,0 +1,451 @@
<?php
namespace Chill\MainBundle\Controller;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Chill\MainBundle\Entity\User;
use Chill\MainBundle\Form\UserType;
use Chill\MainBundle\Entity\GroupCenter;
use Chill\MainBundle\Form\Type\ComposedGroupCenterType;
use Chill\MainBundle\Form\UserPasswordType;
/**
* Class UserController
*
* @package Chill\MainBundle\Controller
*/
class UserController extends AbstractController
{
const FORM_GROUP_CENTER_COMPOSED = 'composed_groupcenter';
/**
* @var \Psr\Log\LoggerInterface
*/
private $logger;
/**
* UserController constructor.
*
* @param LoggerInterface $logger
*/
public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
}
/**
* Lists all User entities.
*
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$entities = $em->createQuery('SELECT u FROM ChillMainBundle:User u '
. 'ORDER BY u.username')
->getResult();
return $this->render('@ChillMain/User/index.html.twig', array(
'entities' => $entities,
));
}
/**
* Creates a new User entity.
*
*/
public function createAction(Request $request)
{
$user = new User();
$form = $this->createCreateForm($user);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$user->setPassword($this->get('security.password_encoder')
->encodePassword($user, $form['plainPassword']->getData()));
$em->persist($user);
$em->flush();
return $this->redirect($this->generateUrl('admin_user_show', array('id' => $user->getId())));
}
return $this->render('@ChillMain/User/new.html.twig', array(
'entity' => $user,
'form' => $form->createView(),
));
}
/**
* Creates a form to create a User entity.
*
* @param User $entity The entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createCreateForm(User $entity)
{
$form = $this->createForm(UserType::class, $entity, array(
'action' => $this->generateUrl('admin_user_create'),
'method' => 'POST',
'is_creation' => true
));
$form->add('submit', SubmitType::class, array('label' => 'Create'));
return $form;
}
/**
* Displays a form to create a new User entity.
*
*/
public function newAction()
{
$user = new User();
$form = $this->createCreateForm($user);
return $this->render('@ChillMain/User/new.html.twig', array(
'entity' => $user,
'form' => $form->createView(),
));
}
/**
* Finds and displays a User entity.
*
*/
public function showAction($id)
{
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository('ChillMainBundle:User')->find($id);
if (!$user) {
throw $this->createNotFoundException('Unable to find User entity.');
}
return $this->render('@ChillMain/User/show.html.twig', array(
'entity' => $user,
));
}
/**
* Displays a form to edit an existing User entity.
*
*/
public function editAction($id)
{
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository('ChillMainBundle:User')->find($id);
if (!$user) {
throw $this->createNotFoundException('Unable to find User entity.');
}
$editForm = $this->createEditForm($user);
return $this->render('@ChillMain/User/edit.html.twig', array(
'entity' => $user,
'edit_form' => $editForm->createView(),
'add_groupcenter_form' => $this->createAddLinkGroupCenterForm($user)->createView(),
'delete_groupcenter_form' => array_map(
function(\Symfony\Component\Form\Form $form) {
return $form->createView();
},
iterator_to_array($this->getDeleteLinkGroupCenterByUser($user), true))
));
}
/**
* Displays a form to edit the user password.
*
*/
public function editPasswordAction($id)
{
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository('ChillMainBundle:User')->find($id);
if (!$user) {
throw $this->createNotFoundException('Unable to find User entity.');
}
$editForm = $this->createEditPasswordForm($user);
return $this->render('@ChillMain/User/edit_password.html.twig', array(
'entity' => $user,
'edit_form' => $editForm->createView()
));
}
/**
*
*
* @param User $user
* @return \Symfony\Component\Form\Form
*/
private function createEditPasswordForm(User $user)
{
return $this->createForm(UserPasswordType::class, null, array(
'action' =>
$this->generateUrl('admin_user_update_password', array('id' => $user->getId())),
'method' => 'PUT',
'user' => $user
))
->add('submit', SubmitType::class, array('label' => 'Change password'))
->remove('actual_password')
;
}
public function deleteLinkGroupCenterAction($uid, $gcid)
{
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository('ChillMainBundle:User')->find($uid);
if (!$user) {
throw $this->createNotFoundException('Unable to find User entity.');
}
$groupCenter = $em->getRepository('ChillMainBundle:GroupCenter')
->find($gcid);
if (!$groupCenter) {
throw $this->createNotFoundException('Unable to find groupCenter entity');
}
try {
$user->removeGroupCenter($groupCenter);
} catch (\RuntimeException $ex) {
$this->addFlash('error', $this->get('translator')->trans($ex->getMessage()));
return $this->redirect($this->generateUrl('admin_user_edit', array('id' => $uid)));
}
$em->flush();
$this->addFlash('success', $this->get('translator')
->trans('The permissions where removed.'));
return $this->redirect($this->generateUrl('admin_user_edit', array('id' => $uid)));
}
public function addLinkGroupCenterAction(Request $request, $uid)
{
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository('ChillMainBundle:User')->find($uid);
if (!$user) {
throw $this->createNotFoundException('Unable to find User entity.');
}
$form = $this->createAddLinkGroupCenterForm($user);
$form->handleRequest($request);
if ($form->isValid()) {
$groupCenter = $this->getPersistedGroupCenter(
$form[self::FORM_GROUP_CENTER_COMPOSED]->getData());
$user->addGroupCenter($groupCenter);
if ($this->get('validator')->validate($user)->count() === 0) {
$em->flush();
$this->addFlash('success', $this->get('translator')->trans('The '
. 'permissions have been successfully added to the user'));
return $this->redirect($this->generateUrl('admin_user_edit',
array('id' => $uid)));
} else {
foreach($this->get('validator')->validate($user) as $error)
$this->addFlash('error', $error->getMessage());
}
}
return $this->render('@ChillMain/User/edit.html.twig', array(
'entity' => $user,
'edit_form' => $this->createEditForm($user)->createView(),
'add_groupcenter_form' => $this->createAddLinkGroupCenterForm($user)->createView(),
'delete_groupcenter_form' => array_map(
function(\Symfony\Component\Form\Form $form) {
return $form->createView();
},
iterator_to_array($this->getDeleteLinkGroupCenterByUser($user), true))
));
}
private function getPersistedGroupCenter(GroupCenter $groupCenter)
{
$em = $this->getDoctrine()->getManager();
$groupCenterManaged = $em->getRepository('ChillMainBundle:GroupCenter')
->findOneBy(array(
'center' => $groupCenter->getCenter(),
'permissionsGroup' => $groupCenter->getPermissionsGroup()
));
if (!$groupCenterManaged) {
$em->persist($groupCenter);
return $groupCenter;
}
return $groupCenterManaged;
}
/**
* Creates a form to edit a User entity.
*
* @param User $user The entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createEditForm(User $user)
{
$form = $this->createForm(UserType::class, $user, array(
'action' => $this->generateUrl('admin_user_update', array('id' => $user->getId())),
'method' => 'PUT',
));
$form->add('submit', SubmitType::class, array('label' => 'Update'));
return $form;
}
/**
* Edits an existing User entity.
*
*/
public function updateAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository('ChillMainBundle:User')->find($id);
if (!$user) {
throw $this->createNotFoundException('Unable to find User entity.');
}
$editForm = $this->createEditForm($user);
$editForm->handleRequest($request);
if ($editForm->isValid()) {
$em->flush();
return $this->redirect($this->generateUrl('admin_user_edit', array('id' => $id)));
}
return $this->render('@ChillMain/User/edit.html.twig', array(
'entity' => $user,
'edit_form' => $editForm->createView(),
'add_groupcenter_form' => $this->createAddLinkGroupCenterForm($user)->createView(),
'delete_groupcenter_form' => array_map(
function(\Symfony\Component\Form\Form $form) {
return $form->createView();
},
iterator_to_array($this->getDeleteLinkGroupCenterByUser($user), true))
));
}
/**
* Edits the user password
*
*/
public function updatePasswordAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository('ChillMainBundle:User')->find($id);
if (!$user) {
throw $this->createNotFoundException('Unable to find User entity.');
}
$editForm = $this->createEditPasswordForm($user);
$editForm->handleRequest($request);
if ($editForm->isValid()) {
$password = $editForm->get('new_password')->getData();
// logging for prod
$this->logger->info('update password for an user', [
'by' => $this->getUser()->getUsername(),
'user' => $user->getUsername()
]);
$user->setPassword($this->get('security.password_encoder')
->encodePassword($user, $password));
$em->flush();
$this->addFlash('success', $this->get('translator')->trans('Password successfully updated!'));
return $this->redirect($this->generateUrl('admin_user_edit', array('id' => $id)));
}
return $this->render('@ChillMain/User/edit_password.html.twig', array(
'entity' => $user,
'edit_form' => $editForm->createView(),
));
}
/**
* Creates a form to delete a link to a GroupCenter
*
* @param mixed $permissionsGroup The entity id
*
* @return \Symfony\Component\Form\Form The form
*/
private function createDeleteLinkGroupCenterForm(User $user, GroupCenter $groupCenter)
{
return $this->createFormBuilder()
->setAction($this->generateUrl('admin_user_delete_group_center',
array('uid' => $user->getId(), 'gcid' => $groupCenter->getId())))
->setMethod('DELETE')
->add('submit', SubmitType::class, array('label' => 'Delete'))
->getForm()
;
}
/**
* create a form to add a link to a groupcenter
*
* @param User $user
* @return \Symfony\Component\Form\Form
*/
private function createAddLinkGroupCenterForm(User $user)
{
return $this->createFormBuilder()
->setAction($this->generateUrl('admin_user_add_group_center',
array('uid' => $user->getId())))
->setMethod('POST')
->add(self::FORM_GROUP_CENTER_COMPOSED, ComposedGroupCenterType::class)
->add('submit', SubmitType::class, array('label' => 'Add a new groupCenter'))
->getForm()
;
}
/**
*
* @param User $user
*/
private function getDeleteLinkGroupCenterByUser(User $user)
{
foreach ($user->getGroupCenters() as $groupCenter) {
yield $groupCenter->getId() => $this
->createDeleteLinkGroupCenterForm($user, $groupCenter);
}
}
}