first commit symfony 6

This commit is contained in:
2022-07-21 16:15:47 +02:00
parent d9bfbb6b3c
commit 5c4961748b
282 changed files with 37482 additions and 0 deletions

View File

@ -0,0 +1,102 @@
<?php
namespace App\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Finder\Finder;
use App\Entity\Tallyday as Tallyday;
class CleanCommand extends Command
{
private $container;
private $em;
private $output;
private $filesystem;
private $rootlog;
public function __construct(ContainerInterface $container,EntityManagerInterface $em)
{
parent::__construct();
$this->container = $container;
$this->em = $em;
}
protected function configure()
{
$this
->setName('app:Clean')
->setDescription('Nettoyage des données obsolètes')
->setHelp('Nettoyage des données obsolètes')
->addArgument('cronid', InputArgument::OPTIONAL, 'ID Cron Job')
->addArgument('lastchance', InputArgument::OPTIONAL, 'Lastchance to run the cron')
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->output = $output;
$this->filesystem = new Filesystem();
$this->rootlog = $this->container->get('kernel')->getLogDir()."/";
$alias = $this->container->getParameter('appAlias');
$this->writelnred('');
$this->writelnred('== app:Clean');
$this->writelnred('==========================================================================================================');
$now=new \DateTime('now');
$directory=$this->container->get('kernel')->getProjectDir()."/public/uploads/avatar";
$this->writeln($directory);
$files=[];
$fs = new Filesystem();
if($fs->exists($directory)) {
$finder = new Finder();
$finder->in($directory)->files();
foreach (iterator_to_array($finder) as $file) {
$name = $file->getRelativePathname();
if($name!="admin.jpg"&&$name!="noavatar.png"&&$name!="system.jpg") {
$entity=$this->em->getRepository("App\Entity\User")->findBy(["avatar"=>$name]);
if(!$entity) {
$this->writeln($name);
$url=$directory."/".$name;
if($fs->exists($url)) {
$fs->remove($url);
}
}
}
}
}
$fs = new Filesystem();
$users=$this->em->getRepository("App\Entity\User")->findAll();
foreach($users as $user) {
if(!$fs->exists($directory."/".$user->getAvatar())) {
$this->writeln($user->getUsername());
$user->setAvatar("noavatar.png");
$this->em->persist($user);
$this->em->flush();
}
}
$this->writeln('');
return Command::SUCCESS;
}
private function writelnred($string) {
$this->output->writeln('<fg=red>'.$string.'</>');
$this->filesystem->appendToFile($this->rootlog.'cron.log', $string."\n");
}
private function writeln($string) {
$this->output->writeln($string);
$this->filesystem->appendToFile($this->rootlog.'cron.log', $string."\n");
}
}

View File

@ -0,0 +1,81 @@
<?php
namespace App\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Finder\Finder;
use App\Entity\Tallyday as Tallyday;
class CleanRegistrationCommand extends Command
{
private $container;
private $em;
private $output;
private $filesystem;
private $rootlog;
private $byexec;
public function __construct(ContainerInterface $container,EntityManagerInterface $em)
{
parent::__construct();
$this->container = $container;
$this->em = $em;
}
protected function configure()
{
$this
->setName('app:CleanRegistration')
->setDescription('Nettoyage des inscriptions obsolètes')
->setHelp('Nettoyage des inscriptions obsolètes')
->addArgument('cronid', InputArgument::OPTIONAL, 'ID Cron Job')
->addArgument('lastchance', InputArgument::OPTIONAL, 'Lastchance to run the cron')
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->output = $output;
$this->filesystem = new Filesystem();
$this->rootlog = $this->container->get('kernel')->getLogDir()."/";
$this->writelnred('');
$this->writelnred('== app:CleanRegistration');
$this->writelnred('==========================================================================================================');
$now=new \DateTime('now');
$datas = $this->em
->createQueryBuilder()
->select('table')
->from('App\Entity\Registration','table')
->where('table.keyexpire<:now')
->setParameter("now",$now->format("Y-m-d H:i:s"))
->getQuery()
->getResult();
foreach($datas as $data) {
$this->writeln('Inscription supprimée = '.$data->getkeyexpire()->format("Y-m-d H:i:s")." >> ".$data->getUsername());
$this->em->remove($data);
$this->em->flush();
}
$this->writeln('');
return Command::SUCCESS;
}
private function writelnred($string) {
$this->output->writeln('<fg=red>'.$string.'</>');
$this->filesystem->appendToFile($this->rootlog.'cron.log', $string."\n");
if($this->byexec) $this->filesystem->appendToFile($this->rootlog.'exec.log', $string."\n");
}
private function writeln($string) {
$this->output->writeln($string);
$this->filesystem->appendToFile($this->rootlog.'cron.log', $string."\n");
if($this->byexec) $this->filesystem->appendToFile($this->rootlog.'exec.log', $string."\n");
}
}

136
src/Command/CronCommand.php Normal file
View File

@ -0,0 +1,136 @@
<?php
namespace App\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Command\LockableTrait;
use App\Entity\Cron;
class CronCommand extends Command
{
private $container;
private $em;
private $output;
private $filesystem;
private $rootlog;
use LockableTrait;
public function __construct(ContainerInterface $container,EntityManagerInterface $em)
{
parent::__construct();
$this->container = $container;
$this->em = $em;
}
protected function configure()
{
$this
->setName('app:Cron')
->setDescription('Execution of the cron command')
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->output = $output;
$this->filesystem = new Filesystem();
$this->rootlog = $this->container->get('kernel')->getLogDir()."/";
if (!$this->lock()) {
$this->output->writeln("CRON LOCK");
return Command::FAILURE;
}
$crons = $this->em->getRepository('App\Entity\Cron')->toexec();
if($crons) {
$now=new \DateTime();
$this->writelnred('');
$this->writelnred('');
$this->writelnred('');
$this->writelnred('');
$this->writelnred('==========================================================================================================');
$this->writelnred('== CRON ==================================================================================================');
$this->writelnred('==========================================================================================================');
$this->writeln ('Date = '.$now->format('Y-m-d H:i:s'));
$this->writeln ('Application = '.$this->container->getParameter("appName"));
}
foreach($crons as $cron) {
// Id du cron
$idcron = $cron->getId();
// Flag d'execution en cours
$now=new \DateTime();
$cron->setStartexecdate($now);
//$cron->setStatut(1);
$this->em->persist($cron);
$this->em->flush();
// Récupération de la commande
$command = $this->getApplication()->find($cron->getCommand());
// Réccuépration des parametres
$jsonparameter=json_decode($cron->getJsonargument(),true);
// Parametre id du cron actuel
$jsonparameter["cronid"]=$cron->getId();
// Formater la chaine de parametre
$parameter = new ArrayInput($jsonparameter);
// Executer la commande
try{
$returnCode = $command->run($parameter, $output);
}
catch(\Exception $e) {
$this->writelnred("JOB EN ERREUR .".$e->getMessage());
$returnCode=Command::FAILURE;
}
// Flag de fin d'execution
$now=new \DateTime();
$cron->setEndexecdate($now);
// Si interval par heure
if(fmod($cron->getRepeatinterval(),3600)==0)
$next=clone $cron->getNextexecdate();
else
$next=new \DateTime();
$next->add(new \DateInterval('PT'.$cron->getRepeatinterval().'S'));
$cron->setNextexecdate($next);
// Statut OK/KO
$cron->setStatut(($returnCode==Command::FAILURE?0:1));
$this->em->persist($cron);
$this->em->flush();
}
if($crons) {
$this->writelnred("==");
$this->writelnred("FIN CRON");
$this->writelnred("==");
$this->writelnred("");
}
return Command::SUCCESS;
}
private function writelnred($string) {
$this->output->writeln('<fg=red>'.$string.'</>');
$this->filesystem->appendToFile($this->rootlog.'cron.log', $string."\n");
}
private function writeln($string) {
$this->output->writeln($string);
$this->filesystem->appendToFile($this->rootlog.'cron.log', $string."\n");
}
}

571
src/Command/InitCommand.php Normal file
View File

@ -0,0 +1,571 @@
<?php
namespace App\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Filesystem\Filesystem;
use Ramsey\Uuid\Uuid;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\Id\AssignedGenerator;
use App\Entity\Group;
use App\Entity\Niveau01;
use App\Entity\User;
use App\Entity\Config;
use App\Entity\Cron;
class InitCommand extends Command
{
private $container;
private $em;
private $output;
private $filesystem;
private $rootlog;
private $appname;
public function __construct(ContainerInterface $container,EntityManagerInterface $em)
{
parent::__construct();
$this->container = $container;
$this->em = $em;
}
protected function configure()
{
$this
->setName('app:Init')
->setDescription('Init Data for App')
->setHelp('This command Init Data App')
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->output = $output;
$this->filesystem = new Filesystem();
$this->rootlog = $this->container->get('kernel')->getLogDir()."/";
$this->appname = $this->container->getParameter('appName');
$this->writeln('APP = Default Data');
// On s'assure que le groupe tout le monde existe
$metadata = $this->em->getClassMetaData('App\Entity\Group');
$metadata->setIdGeneratorType(ClassMetadata::GENERATOR_TYPE_NONE);
$metadata->setIdGenerator(new AssignedGenerator());
$group=$this->em->getRepository('App\Entity\Group')->findOneBy(['id'=>'-1']);
if(!$group) {
$group=new Group();
$group->setId(-1);
$group->setLabel("Tout le monde");
$group->setIsopen(false);
$group->setIsworkgroup(false);
$group->setApikey(Uuid::uuid4());
$this->em->persist($group);
$this->em->flush();
}
// On s'assure qu'il exite un niveau01
$metadata = $this->em->getClassMetaData('App\Entity\Niveau01');
$metadata->setIdGeneratorType(ClassMetadata::GENERATOR_TYPE_NONE);
$metadata->setIdGenerator(new AssignedGenerator());
$niveau01=$this->em->getRepository('App\Entity\Niveau01')->findOneBy(['id'=>'-1']);
if(!$niveau01) {
$niveau01=new Niveau01();
$niveau01->setId(-1);
$niveau01->setLabel($this->appname);
$niveau01->setApikey(Uuid::uuid4());
$this->em->persist($niveau01);
$this->em->flush();
}
// On s'assure que le user admin existe
$metadata = $this->em->getClassMetaData('App\Entity\User');
$metadata->setIdGeneratorType(ClassMetadata::GENERATOR_TYPE_NONE);
$metadata->setIdGenerator(new AssignedGenerator());
$user=$this->em->getRepository('App\Entity\User')->findOneBy(['id'=>'-1']);
if(!$user) {
$user=new User();
$user->setId(-1);
$user->setUsername("admin");
$user->setFirstname("admin");
$user->setLastname($this->appname);
$user->setPassword($this->container->getParameter('appSecret'));
$user->setEmail($this->container->getParameter('appMailnoreply'));
$user->setApikey(Uuid::uuid4());
$user->setAvatar("admin.jpg");
$user->setIsVisible(true);
$user->setNiveau01($niveau01);
$this->em->persist($user);
$this->em->flush();
}
// On s'assure que les appAdmins sont bien admin
foreach($this->container->getParameter('appAdmins') as $admin) {
$user=$this->em->getRepository('App\Entity\User')->findOneBy(['username'=>$admin]);
if($user&&!$user->hasRole("ROLE_ADMIN")) {
$user->setRole("ROLE_ADMIN");
$this->em->flush();
}
}
// colorbgbody = Couleur des fonds de page
$this->insertConfig(
1, // order
"site", // category
"appname", // id
"Titre de votre site", // title
"", // value
$this->appname, // default
"string", // type,
true, // visible
true, // changeable
false, // required
"", // grouped
"Titre de votre site"
);
$this->insertConfig(
2, // order
"site", // category
"appsubname", // id
"Sous-titre de votre site", // title
"", // value
"", // default
"string", // type,
true, // visible
true, // changeable
false, // required
"", // grouped
"Sous-titre de votre site"
);
$this->insertConfig(
3, // order
"site", // category
"appdescription", // id
"Description de votre site", // title
"", // value
"", // default
"editor", // type,
true, // visible
true, // changeable
false, // required
"", // grouped
"Description de votre site"
);
$this->insertConfig(
100, // order
"site", // category
"fgforceconnect", // id
"Forcer la connexion", // title
"", // value
"0", // default
"boolean", // type,
true, // visible
true, // changeable
true, // required
"", // grouped
"Forcer la connexion afin de rendre votre site privé"
);
$this->insertConfig(
200, // order
"site", // category
"permgroup", // id
"Rôle créateur de groupe de travail", // title
"", // value
"ROLE_MASTER", // default
"role", // type,
true, // visible
true, // changeable
true, // required
"", // grouped
"Détermine quel rôle aura la permission de créer des groupes de travail"
);
$this->insertConfig(
201, // order
"site", // category
"permannu", // id
"Rôle accédant à l'annuaire", // title
"", // value
"ROLE_USER", // default
"role", // type,
true, // visible
true, // changeable
true, // required
"", // grouped
"Détermine quel rôle aura la permission de voir l'annuaire"
);
$this->insertConfig(
202, // order
"site", // category
"scopeannu", // id
"Scope de l'annuaire", // title
"", // value
"ALL", // default
"scopeannu", // type,
true, // visible
true, // changeable
true, // required
"", // grouped
"Détermine le scope des utilisateurs visibles dans l'annuaire par d'autres utilisateurs"
);
$this->insertConfig(
500, // order
"site", // category
"apptheme", // id
"Thème de votre site", // title
"", // value
"", // default
"string", // type,
false, // visible
true, // changeable
false, // required
"", // grouped
"Thème de votre site"
);
// colorbgbody = Couleur des fonds de page
$this->insertConfig(
1, // order
"colorbgbody", // category
"colorbgbodydark", // id
"Couleur de fond fonçée", // title
"", // value
"#2e3131", // default
"color", // type,
true, // visible
true, // changeable
false, // required
"", // grouped
"La couleur de fond quand le site a besoin d'avoir une couleur de fond foncée"
);
$this->insertConfig(
2, // order
"colorbgbody", // category
"colorbgbodylight", // id
"Couleur de fond claire", // title
"", // value
"#ffffff", // default
"color", // type,
true, // visible
true, // changeable
false, // required
"", // grouped
"La couleur de fond quand le site a besoin d'avoir une couleur de fond claire"
);
// colorfttitle = Couleur des fontes titre
$this->insertConfig(
1, // order
"colorfttitle", // category
"colorfttitledark", // id
"Couleur des titres sur fond fonçé", // title
"", // value
"#ffffff", // default
"color", // type,
true, // visible
true, // changeable
false, // required
"", // grouped
"La couleur des titres sur fond fonçé"
);
$this->insertConfig(
2, // order
"colorfttitle", // category
"colorfttitlelight", // id
"Couleur des titres sur fond claire", // title
"", // value
"#2e3131", // default
"color", // type,
true, // visible
true, // changeable
false, // required
"", // grouped
"La couleur des titres sur fond claire"
);
// colorftbody = Couleur des fontes titre
$this->insertConfig(
1, // order
"colorftbody", // category
"colorftbodydark", // id
"Couleur de la police sur fond fonçé", // title
"", // value
"#ffffff", // default
"color", // type,
true, // visible
true, // changeable
false, // required
"", // grouped
"La couleur de la police sur fond fonçé"
);
$this->insertConfig(
2, // order
"colorftbody", // category
"colorftbodylight", // id
"Couleur de la police sur fond claire", // title
"", // value
"#343a40", // default
"color", // type,
true, // visible
true, // changeable
false, // required
"", // grouped
"La couleur de la police sur fond claire"
);
// font = nom des polices
$this->insertConfig(
1, // order
"font", // category
"fonttitle", // id
"Police pour les titres", // title
"", // value
"Theboldfont", // default
"font", // type,
true, // visible
true, // changeable
false, // required
"", // grouped
"La couleur de la police de votre site"
);
$this->insertConfig(
2, // order
"font", // category
"fontbody", // id
"Police principale", // title
"", // value
"Roboto-Regular", // default
"font", // type,
true, // visible
true, // changeable
false, // required
"", // grouped
"Nom de la police principale"
);
$this->insertConfig(
3, // order
"font", // category
"fontsizeh1", // id
"Taille des titres h1", // title
"", // value
"40", // default
"integer", // type,
true, // visible
true, // changeable
false, // required
"", // grouped
"Taille des titres h1 en px"
);
$this->insertConfig(
4, // order
"font", // category
"fontsizeh2", // id
"Taille des titres h2", // title
"", // value
"32", // default
"integer", // type,
true, // visible
true, // changeable
false, // required
"", // grouped
"Taille des titres h2 en px"
);
$this->insertConfig(
5, // order
"font", // category
"fontsizeh3", // id
"Taille des titres h3", // title
"", // value
"28", // default
"integer", // type,
true, // visible
true, // changeable
false, // required
"", // grouped
"Taille des titres h3 en px"
);
$this->insertConfig(
6, // order
"font", // category
"fontsizeh4", // id
"Taille des titres h4", // title
"", // value
"24", // default
"integer", // type,
true, // visible
true, // changeable
false, // required
"", // grouped
"Taille des titres h4 en px"
);
// logo =
$this->insertConfig(
1, // order
"logo", // category
"logodark", // id
"Logo sur fond fonçé", // title
"", // value
"logo.png", // default
"logo", // type,
true, // visible
true, // changeable
false, // required
"", // grouped
"Logo sur fond fonçé"
);
$this->insertConfig(
2, // order
"logo", // category
"logolight", // id
"Logo sur fond clair", // title
"", // value
"logo.png", // default
"logo", // type,
true, // visible
true, // changeable
false, // required
"", // grouped
"Logo sur fond clair"
);
// header =
$this->insertConfig(
1, // order
"header", // category
"headerimage", // id
"Image de fond de la bannière", // title
"", // value
"header.jpg", // default
"header", // type,
true, // visible
true, // changeable
false, // required
"", // grouped
"Image appnamede fond de la bannière"
);
$this->insertConfig(
1, // order
"header", // category
"headerheight", // id
"Hauteur de la bannière", // title
"", // value
"100", // default
"integer", // type,
true, // visible
true, // changeable
false, // required
"", // grouped
"Image de fond de la bannière"
);
$output->writeln('');
// Job de purge des fichiers obsolète
// Toute les 24h à 3h00
$entity = $this->em->getRepository('App\Entity\Cron')->findOneBy(["command"=>"app:Clean"]);
if(!$entity) {
$entity = new Cron;
$nextdate=$entity->getSubmitdate();
$nextdate->setTime(3,0);
$entity->setCommand("app:Clean");
$entity->setDescription("Nettoyage des données obsolètes");
$entity->setStatut(1);
$entity->setRepeatinterval(86400);
$entity->setNextexecdate($nextdate);
$this->em->persist($entity);
}
// Job synchronisation des comptes utilisateur
// Toute les 24h à 3h00
$entity = $this->em->getRepository('App\Entity\Cron')->findOneBy(["command"=>"app:Synchro"]);
if(!$entity) {
$entity = new Cron;
$nextdate=$entity->getSubmitdate();
$nextdate->setTime(4,0);
$entity->setCommand("app:Synchro");
$entity->setDescription("Synchronisation des comptes utilisateurs");
$entity->setStatut(1);
$entity->setRepeatinterval(86400);
$entity->setNextexecdate($nextdate);
$this->em->persist($entity);
}
// Job purge des registrations obsolètes
// Toute les 5mn
$entity = $this->em->getRepository('App\Entity\Cron')->findOneBy(["command"=>"app:CleanRegistration"]);
if(!$entity) {
$entity = new Cron;
$entity->setCommand("app:CleanRegistration");
$entity->setDescription("Nettoyage des Inscriptions obsolètes");
$entity->setStatut(1);
$entity->setRepeatinterval(300);
$entity->setNextexecdate($entity->getSubmitdate());
$this->em->persist($entity);
}
$this->em->flush();
$output->writeln('');
return Command::SUCCESS;
}
private function insertConfig($order,$category,$id,$title,$value,$default,$type,$visible,$changeable,$required,$grouped,$help) {
$entity=$this->em->getRepository("App\Entity\Config")->find($id);
if(!$entity) {
$entity= new Config();
$entity->setId($id);
$entity->setValue($value);
}
$entity->setDefault($default);
$entity->setCategory($category);
$entity->setOrder($order);
$entity->setTitle($title);
$entity->setType($type);
$entity->setVisible($visible);
$entity->setChangeable($changeable);
$entity->setRequired($required);
$entity->setGrouped($grouped);
$entity->setHelp($help);
$this->em->persist($entity);
$this->em->flush();
}
private function writelnred($string) {
$this->output->writeln('<fg=red>'.$string.'</>');
$this->filesystem->appendToFile($this->rootlog.'cron.log', $string."\n");
}
private function writeln($string) {
$this->output->writeln($string);
$this->filesystem->appendToFile($this->rootlog.'cron.log', $string."\n");
}
}

View File

@ -0,0 +1,83 @@
<?php
namespace App\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Filesystem\Filesystem;
use Cadoles\CoreBundle\Entity\User;
class SetPasswordCommand extends Command
{
private $container;
private $em;
private $output;
private $filesystem;
private $rootlog;
public function __construct(ContainerInterface $container,EntityManagerInterface $em)
{
parent::__construct();
$this->container = $container;
$this->em = $em;
}
protected function configure()
{
$this
->setName('app:SetPassword')
->setDescription("Modifier le password d'un utilisateur")
->setHelp("Modifier le password d'un utilisateur")
->addArgument('username', InputArgument::OPTIONAL, 'username')
->addArgument('password', InputArgument::OPTIONAL, 'password')
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->output = $output;
$this->filesystem = new Filesystem();
$this->rootlog = $this->container->get('kernel')->getLogDir()."/";
$this->writelnred('');
$this->writelnred('== app:SetPasword');
$this->writelnred('==========================================================================================================');
$username = $input->getArgument('username');
$this->writeln($username);
$password = $input->getArgument('password');
$this->writeln($password);
$user = $this->em->getRepository('App\Entity\User')->findOneBy(array('username' => $username));
if($user) {
// Set Password
$user->setPassword($password);
$this->em->persist($user);
$this->em->flush();
}
$this->writeln('');
return Command::SUCCESS;
}
private function writelnred($string) {
$this->output->writeln('<fg=red>'.$string.'</>');
$this->filesystem->appendToFile($this->rootlog.'cron.log', $string."\n");
}
private function writeln($string) {
if(!$string) $string=" ";
$this->output->writeln($string);
$this->filesystem->appendToFile($this->rootlog.'cron.log', $string."\n");
}
}

View File

@ -0,0 +1,912 @@
<?php
namespace App\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Filesystem\Filesystem;
use Ramsey\Uuid\Uuid;
use App\Service\LdapService;
use App\Service\ApiService;
use App\Entity\Niveau01;
use App\Entity\Niveau02;
use App\Entity\User;
use App\Entity\Group;
use App\Entity\UserGroup;
class SynchroCommand extends Command
{
public function __construct(ContainerInterface $container,EntityManagerInterface $em,LdapService $ldapservice,ApiService $apiservice)
{
parent::__construct();
$this->container = $container;
$this->em = $em;
$this->ldap = $ldapservice;
$this->apiservice = $apiservice;
}
protected function configure()
{
$this
->setName('app:Synchro')
->setDescription('Synchronisation Annuaire')
->setHelp('This command Synchro for Core')
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->output = $output;
$this->filesystem = new Filesystem();
$this->rootlog = $this->container->get('kernel')->getLogDir()."/";
$this->appMasteridentity = $this->container->getParameter('appMasteridentity');
$appSynchro = $this->container->getParameter('appSynchro');
$this->synchro = $this->container->getParameter("appSynchro");
$this->synchropurgeniveau01 = $this->container->getParameter("appSynchroPurgeNiveau01");
$this->synchropurgeniveau02 = $this->container->getParameter("appSynchroPurgeNiveau02");
$this->synchropurgegroup = $this->container->getParameter("appSynchroPurgeGroup");
$this->synchropurgeuser = $this->container->getParameter("appSynchroPurgeUser");
$this->host = $this->container->getParameter("ldapHost");
$this->port = $this->container->getParameter("ldapPort");
$this->usetls = $this->container->getParameter("ldapUsetls");
$this->userwriter = $this->container->getParameter("ldapUserwriter");
$this->user = $this->container->getParameter("ldapUser");
$this->password = $this->container->getParameter("ldapPassword");
$this->basedn = $this->container->getParameter("ldapBasedn");
$this->baseorganisation = $this->container->getParameter("ldapBaseorganisation");
$this->baseniveau01 = $this->container->getParameter("ldapBaseniveau01");
$this->baseniveau02 = $this->container->getParameter("ldapBaseniveau02");
$this->basegroup = $this->container->getParameter("ldapBasegroup");
$this->baseuser = $this->container->getParameter("ldapBaseuser");
$this->username = $this->container->getParameter("ldapUsername");
$this->firstname = $this->container->getParameter("ldapFirstname");
$this->lastname = $this->container->getParameter("ldapLastname");
$this->email = $this->container->getParameter("ldapEmail");
$this->avatar = $this->container->getParameter("ldapAvatar");
$this->memberof = $this->container->getParameter("ldapMemberof");
$this->groupgid = $this->container->getParameter("ldapGroupgid");
$this->groupname = $this->container->getParameter("ldapGroupname");
$this->groupmember = $this->container->getParameter("ldapGroupmember");
$this->groupmemberisdn = $this->container->getParameter("ldapGroupmemberisdn");
$this->filtergroup = $this->container->getParameter("ldapFiltergroup");
$this->filteruser = $this->container->getParameter("ldapFilteruser");
switch($appSynchro){
case "LDAP2NINE":
$return=$this->ldap2nine();
break;
case "NINE2LDAP":
$return=$this->nine2ldap();
break;
case "NINE2NINE":
$return=$this->nine2nine();
break;
}
$this->writeln('');
return $return;
}
private function ldap2nine()
{
$this->writelnred('');
$this->writelnred('== app:Synchro');
$this->writelnred('==========================================================================================================');
// Synchronisation ldap2nine possible uniquement si appMasteridentity=LDAP or SSO
if($this->appMasteridentity!="LDAP"&&$this->appMasteridentity!="SSO") {
$this->writeln("Synchronisation impossible si appMasteridentity!=LDAP et appMasteridentity!=SSO");
return Command::FAILURE;
}
// Synchronisation impossible si aucune connexion à l'annuaire
if(!$this->ldap->connect()) {
$this->writeln("Synchronisation impossible connexion impossible à l'annuaire");
return Command::FAILURE;
}
$this->writeln('');
$this->writeln('=====================================================');
$this->writeln('== SYNCHONISATION LDAP TO NINE ======================');
$this->writeln('=====================================================');
$tbniveau01members=[];
$tbgroupmembers=[];
$tbniveau01s=[];
$tbgroups=[];
$tbusers=[];
$ldapniveau01s=$this->em->createQueryBuilder()->select('entity')->from('App:Niveau01','entity')->where('entity.ldapfilter IS NOT NULL')->getQuery()->getResult();
$ldapgroups=$this->em->createQueryBuilder()->select('entity')->from('App:Group','entity')->where('entity.ldapfilter IS NOT NULL')->getQuery()->getResult();
$fgsynchroniveau01s=(!empty($this->baseniveau01)&&!empty($this->groupgid)&&!empty($this->groupname)&&!empty($this->filtergroup));
$fgsynchrogroups=(!empty($this->basegroup)&&!empty($this->groupgid)&&!empty($this->groupname)&&!empty($this->filtergroup));
$fgsynchrousers=(!empty($this->baseuser)&&!empty($this->username)&&!empty($this->email)&&!empty($this->filteruser));
$fgsynchropurgeniveau01s=($fgsynchroniveau01s&&$this->synchropurgeniveau01);
$fgsynchropurgegroups=($fgsynchrogroups&&$this->synchropurgegroup);
$fgsynchropurgeusers=($fgsynchrousers&&$this->synchropurgeuser);
// Synchronisation des niveau01s
if($fgsynchroniveau01s) {
$this->writeln('');
$this->writeln('== NIVEAU01 =========================================');
$ldapentrys=$this->ldap->search($this->filtergroup,[$this->groupgid,$this->groupname,$this->groupmember],$this->baseniveau01);
foreach($ldapentrys as $ldapentry) {
$niveau01other=$this->em->getRepository("App\Entity\Niveau01")->findOneBy(["label"=>$ldapentry[$this->groupname]]);
if($niveau01other&&$niveau01other->getIdexternal()!=$ldapentry[$this->groupgid]) {
$this->writelnred(" > ".$ldapentry[$this->groupname]." = Impossible à synchroniser un autre niveau01 existe déjà avec ce label");
continue;
}
// On recherche le groupe via le gid
$this->writeln(' > '.$ldapentry[$this->groupname]);
$niveau01=$this->em->getRepository("App\Entity\Niveau01")->findOneBy(["idexternal"=>$ldapentry[$this->groupgid]]);
if(!$niveau01) {
$niveau01=new Niveau01();
$niveau01->setApikey(Uuid::uuid4());
$this->em->persist($niveau01);
}
$niveau01->setIdexternal($ldapentry[$this->groupgid]);
$niveau01->setLabel($ldapentry[$this->groupname]);
$niveau01->setLdapfilter("(".$this->groupname."=".$ldapentry[$this->groupname].")");
$this->em->flush();
// Sauvegarde du niveau01ldap
array_push($tbniveau01s,$ldapentry[$this->groupname]);
// Sauvegarde des membres du niveau01
if(!empty($ldapentry[$this->groupmember])) {
if(!is_array($ldapentry[$this->groupmember])) {
$member=$ldapentry[$this->groupmember];
if(!array_key_exists($member,$tbniveau01members)) $tbniveau01members[$member]=[];
array_push($tbniveau01members[$member],$ldapentry[$this->groupname]);
}
else {
foreach($ldapentry[$this->groupmember] as $member) {
if(!array_key_exists($member,$tbniveau01members)) $tbniveau01members[$member]=[];
array_push($tbniveau01members[$member],$ldapentry[$this->groupname]);
}
}
}
}
}
else {
$this->writeln('');
$this->writeln('== NIVEAU01 =========================================');
$this->writelnred(" > Synchronisation impossible il vous manque des paramétres ldap pour le faire");
}
// Synchronisation des groups
if($fgsynchrogroups) {
$this->writeln('');
$this->writeln('== GROUP ============================================');
$ldapentrys=$this->ldap->search($this->filtergroup,[$this->groupgid,$this->groupname,$this->groupmember],$this->basegroup);
foreach($ldapentrys as $ldapentry) {
$groupother=$this->em->getRepository("App\Entity\Group")->findOneBy(["label"=>$ldapentry[$this->groupname]]);
if($groupother&&$groupother->getIdexternal()!=$ldapentry[$this->groupgid]) {
$this->writelnred(" > ".$ldapentry[$this->groupname]." = Impossible à synchroniser un autre groupe existe déjà avec ce label");
continue;
}
// On recherche le groupe via le gid
$this->writeln(' > '.$ldapentry[$this->groupname]);
$group=$this->em->getRepository("App\Entity\Group")->findOneBy(["idexternal"=>$ldapentry[$this->groupgid]]);
if(!$group) {
$group=new Group();
$group->setIsopen(false);
$group->setIsworkgroup(false);
$group->setApikey(Uuid::uuid4());
$this->em->persist($group);
}
$group->setIdexternal($ldapentry[$this->groupgid]);
$group->setLabel($ldapentry[$this->groupname]);
$group->setLdapfilter("(".$this->groupname."=".$ldapentry[$this->groupname].")");
$this->em->flush();
// Sauvegarde du groupldap
array_push($tbgroups,$ldapentry[$this->groupname]);
// Sauvegarde des membres du group
if(!empty($ldapentry[$this->groupmember])) {
if(!is_array($ldapentry[$this->groupmember])) {
$member=$ldapentry[$this->groupmember];
if(!array_key_exists($member,$tbgroupmembers)) $tbgroupmembers[$member]=[];
array_push($tbgroupmembers[$member],$ldapentry[$this->groupname]);
}
else {
foreach($ldapentry[$this->groupmember] as $member) {
if(!array_key_exists($member,$tbgroupmembers)) $tbgroupmembers[$member]=[];
array_push($tbgroupmembers[$member],$ldapentry[$this->groupname]);
}
}
}
}
}
else {
$this->writeln('');
$this->writeln('== GROUP ============================================');
$this->writelnred(" > Synchronisation impossible il vous manque des paramétres ldap pour le faire");
}
// Synchronisation des users
if($fgsynchrousers) {
$this->writeln('');
$this->writeln('== USER =============================================');
$ldapentrys=$this->ldap->search($this->filteruser,[$this->username,$this->firstname,$this->lastname,$this->email,$this->avatar,$this->memberof],$this->baseuser);
foreach($ldapentrys as $ldapentry) {
$userother=$this->em->getRepository("App\Entity\User")->findOneBy(["email"=>$ldapentry[$this->email]]);
if($userother&&$userother->getUSername()!=$ldapentry[$this->username]) {
$this->writelnred(" > ".$ldapentry[$this->groupname]." = Impossible à synchroniser un autre user existe déjà avec ce mail");
continue;
}
$userother=$this->em->getRepository("App\Entity\Registration")->findOneBy(["email"=>$ldapentry[$this->email]]);
if($userother&&$userother->getUSername()!=$ldapentry[$this->username]) {
$this->writelnred(" > ".$ldapentry[$this->username]." = Impossible à synchroniser un autre user existe déjà avec ce mail");
continue;
}
// On recherche le user via le username
$this->writeln(' > '.$ldapentry[$this->username]);
$user=$this->em->getRepository("App\Entity\User")->findOneBy(["username"=>$ldapentry[$this->username]]);
if(!$user) {
$user=new User();
$user->setUsername($ldapentry[$this->username]);
$user->setIsvisible(true);
$user->setApikey(Uuid::uuid4());
$user->setPassword("LDAPPWD-".$ldapentry[$this->username]);
$user->setRole("ROLE_USER");
$user->setAvatar("noavatar.png");
$this->em->persist($user);
}
// Recherche du niveau01
$niveau01=null;
if($user->getNiveau01()&&empty($user->getNiveau01()->getIdexternal()))
$niveau01=$user->getNiveau01();
if(array_key_exists($ldapentry[$this->username],$tbniveau01members))
$niveau01=$this->em->getRepository("App\Entity\Niveau01")->findOneBy(["label"=>$tbniveau01members[$ldapentry[$this->username]][0]]);
if(!$niveau01)
$niveau01=$this->em->getRepository('App\Entity\Niveau01')->find(-1);
// Mise à jour des attributs
if(!empty($ldapentry[$this->lastname])) $user->setLastname($ldapentry[$this->lastname]);
if(!empty($ldapentry[$this->firstname])) $user->setFirstname($ldapentry[$this->firstname]);
if(!empty($ldapentry[$this->email])) $user->setEmail($ldapentry[$this->email]);
if(!empty($ldapentry[$this->avatar])) $user->setAvatar($ldapentry[$this->avatar]);
// Mise à jour du niveau01
if($niveau01!=$user->getNiveau01()) $user->setNiveau02(null);
$user->setNiveau01($niveau01);
// Mise à jour du role
if(in_array($ldapentry[$this->username],$this->container->getParameter("appAdmins")))
$user->setRole("ROLE_ADMIN");
// Sauvegarde en bdd
$this->em->flush();
// Sauvegarde du userldap
array_push($tbusers,$ldapentry[$this->username]);
// Inscription au groupe
if(array_key_exists($ldapentry[$this->username],$tbgroupmembers)) {
foreach($tbgroupmembers[$ldapentry[$this->username]] as $grouplabel) {
$group=$this->em->getRepository("App\Entity\Group")->findOneBy(["label"=>$grouplabel]);
if($group) {
$usergroup=$this->em->getRepository("App\Entity\UserGroup")->findOneBy(["user"=>$user,"group"=>$group]);
if(!$usergroup) {
$usergroup=new UserGroup();
$usergroup->setUser($user);
$usergroup->setGroup($group);
$usergroup->setApikey(Uuid::uuid4());
$usergroup->setRolegroup(0);
$this->em->persist($usergroup);
$this->em->flush();
}
}
}
}
// Desinscription des group ldap
foreach($ldapgroups as $group) {
if(!array_key_exists($ldapentry[$this->username],$tbgroupmembers)||!in_array($group->getLabel(),$tbgroupmembers[$ldapentry[$this->username]])) {
$usergroup=$this->em->getRepository("App\Entity\UserGroup")->findOneBy(["user"=>$user,"group"=>$group]);
if($usergroup) {
$this->em->remove($usergroup);
$this->em->flush();
}
}
}
}
}
else {
$this->writeln('');
$this->writeln('== USER =============================================');
$this->writelnred(" > Synchronisation impossible il vous manque des paramétres ldap pour le faire");
}
// Purge des users
if($fgsynchropurgeusers) {
$this->writeln('');
$this->writeln('== PURGE USER =============================================');
$users=$this->em->getRepository("App\Entity\User")->findAll();
foreach($users as $user) {
if(!in_array($user->getUsername(),$tbusers)) {
if($user->getId()>0) {
$this->writeln(' > '.$user->getUSername());
$this->em->remove($user);
$this->em->flush();
}
}
}
}
// Purge des groups
if($fgsynchropurgegroups) {
$this->writeln('');
$this->writeln('== PURGE GROUP =============================================');
foreach($ldapgroups as $group) {
if(!in_array($group->getLabel(),$tbgroups)) {
if($group->getId()>0) {
$this->writeln(' > '.$group->getLabel());
$this->em->remove($group);
}
else {
$group->setLdapfilter(null);
$group->setIdexternal(null);
}
$this->em->flush();
}
}
}
// Purge des niveau01s
if($fgsynchropurgeniveau01s) {
$this->writeln('');
$this->writeln('== PURGE NIVEAU01 =============================================');
foreach($ldapniveau01s as $niveau01) {
if(!in_array($niveau01->getLabel(),$tbniveau01s)) {
if($niveau01->getId()>0) {
$user=$this->em->getRepository("App\Entity\User")->findOneBy(["niveau01"=>$niveau01]);
if($user) {
$resetniveau01=$this->em->getRepository("App\Entity\User")->find(-1);
$user->setNiveau01($resetniveau01);
$user->setNiveau02(null);
}
$this->writeln(' > '.$niveau01->getLabel());
$this->em->remove($niveau01);
}
else {
$niveau01->setLdapfilter(null);
$niveau01->setIdexternal(null);
}
$this->em->flush();
}
}
}
return Command::SUCCESS;
}
private function nine2ldap()
{
$this->writelnred('');
$this->writelnred('== app:Synchro');
$this->writelnred('==========================================================================================================');
// Synchronisation impossible si aucune connexion à l'annuaire
if(!$this->ldap->isNine2Ldap()) {
$this->writeln("Synchronisation impossible soit :");
$this->writeln("- connexion impossible à l'annuaire");
$this->writeln("- appMasteridentity!=SQL");
$this->writeln("- votre user ldap n'a pas de permission en écriture");
$this->writeln("- vous n'avez pas renseigné les bases de votre organisation");
return Command::FAILURE;
}
$this->writeln('');
$this->writeln('=====================================================');
$this->writeln('== SYNCHONISATION NINE TO LDAP ======================');
$this->writeln('=====================================================');
$this->writeln('');
$this->writeln('== ORGANISATION =====================================');
$this->writeln($this->baseorganisation);
$this->writeln($this->baseniveau01);
$this->writeln($this->baseniveau02);
$this->writeln($this->basegroup);
$this->writeln($this->baseuser);
$this->ldap->addOrganisations();
$this->writeln('');
$this->writeln('== USER =============================================');
$users=$this->em->getRepository("App\Entity\User")->findAll();
$attributes=$this->ldap->listAttributesUser();
foreach($users as $user) {
$filter=str_replace("*",$user->getUsername(),$this->filteruser);
$ldapentrys=$this->ldap->search($filter,$attributes,$this->baseuser);
if(empty($ldapentrys)) {
$this->writeln($user->getUsername()." = SUBMIT");
$this->ldap->addUser($user);
}
elseif($this->ldap->ismodifyUser($user,$ldapentrys[0])) {
$this->writeln($user->getUsername()." = UPDATE");
$this->ldap->modifyUser($user);
}
}
$ldapentrys=$this->ldap->search($this->filteruser,$attributes,$this->baseuser);
foreach($ldapentrys as $ldapentry) {
$user=$this->em->getRepository("App\Entity\User")->findOneBy(["username"=>$ldapentry["uid"]]);
if(!$user) {
$this->writeln($ldapentry["uid"]." = DELETE");
$dn=$this->ldap->getUserDN($ldapentry["uid"]);
$this->ldap->deleteByDN($dn);
}
}
$this->writeln('');
$this->writeln('== GROUP ============================================');
$groups=$this->em->getRepository("App\Entity\Group")->findAll();
$attributes=$this->ldap->listAttributesGroup();
foreach($groups as $group) {
if($group->getLdapfilter()) {
$group->setLdapfilter(null);
$this->em->flush();
}
$filter="gidnumber=".$group->getId();
$ldapentrys=$this->ldap->search($filter,$attributes,$this->basegroup);
if(empty($ldapentrys)) {
$this->writeln($group->getLabel()." = SUBMIT");
$this->ldap->addGroup($group);
}
elseif($this->ldap->ismodifyGroup($group,$ldapentrys[0])) {
$this->writeln($group->getLabel()." = UPDATE");
$this->ldap->modifyGroup($group,$ldapentrys[0]["cn"]);
}
}
$ldapentrys=$this->ldap->search($this->filtergroup,$attributes,$this->basegroup);
foreach($ldapentrys as $ldapentry) {
$group=$this->em->getRepository("App\Entity\Group")->find($ldapentry["gidnumber"]);
if(!$group) {
$this->writeln($ldapentry["cn"]." = DELETE");
$dn=$this->ldap->getGroupDN($ldapentry["cn"]);
$this->ldap->deleteByDN($dn);
}
}
$this->writeln('');
$this->writeln('== NIVEAU02 =========================================');
$niveau02s=$this->em->getRepository("App\Entity\Niveau02")->findAll();
$attributes=$this->ldap->listAttributesNiveau02();
foreach($niveau02s as $niveau02) {
$filter="gidnumber=".$niveau02->getId();
$ldapentrys=$this->ldap->search($filter,$attributes,$this->baseniveau02);
if(empty($ldapentrys)) {
$this->writeln($niveau02->getLabel()." = SUBMIT");
$this->ldap->addNiveau02($niveau02);
}
elseif($this->ldap->ismodifyNiveau02($niveau02,$ldapentrys[0])) {
$this->writeln($niveau02->getLabel()." = UPDATE");
$this->ldap->modifyNiveau02($niveau02,$ldapentrys[0]["cn"]);
}
}
$ldapentrys=$this->ldap->search($this->filtergroup,$attributes,$this->baseniveau02);
foreach($ldapentrys as $ldapentry) {
$niveau02=$this->em->getRepository("App\Entity\Niveau02")->find($ldapentry["gidnumber"]);
if(!$niveau02) {
$this->writeln($ldapentry["cn"]." = DELETE");
$dn=$this->ldap->getNiveau02DN($ldapentry["cn"]);
$this->ldap->deleteByDN($dn);
}
}
$this->writeln('');
$this->writeln('== NIVEAU01 =========================================');
$niveau01s=$this->em->getRepository("App\Entity\Niveau01")->findAll();
$attributes=$this->ldap->listAttributesNiveau01();
foreach($niveau01s as $niveau01) {
if($niveau01->getLdapfilter()) {
$niveau01->setLdapfilter(null);
$this->em->flush();
}
$filter="gidnumber=".$niveau01->getId();
$ldapentrys=$this->ldap->search($filter,$attributes,$this->baseniveau01);
if(empty($ldapentrys)) {
$this->writeln($niveau01->getLabel()." = SUBMIT");
$this->ldap->addNiveau01($niveau01);
}
elseif($this->ldap->ismodifyNiveau01($niveau01,$ldapentrys[0])) {
$this->writeln($niveau01->getLabel()." = UPDATE");
$this->ldap->modifyNiveau01($niveau01,$ldapentrys[0]["cn"]);
}
}
$ldapentrys=$this->ldap->search($this->filtergroup,$attributes,$this->baseniveau01);
foreach($ldapentrys as $ldapentry) {
$niveau01=$this->em->getRepository("App\Entity\Niveau01")->find($ldapentry["gidnumber"]);
if(!$niveau01) {
$this->writeln($ldapentry["cn"]." = DELETE");
$dn=$this->ldap->getNiveau01DN($ldapentry["cn"]);
$this->ldap->deleteByDN($dn);
}
}
return Command::SUCCESS;
}
private function nine2nine()
{
$this->writelnred('');
$this->writelnred('== app:Synchro');
$this->writelnred('==========================================================================================================');
// Synchronisation ldap2nine possible uniquement si appMasteridentity=NINE
if($this->appMasteridentity!="NINE") {
$this->writeln("Synchronisation impossible si appMasteridentity!=NINE");
return Command::FAILURE;
}
$nineurl = $this->container->getParameter("nineUrl");
$ninesecret = $this->container->getParameter("nineSecret");
if(!$nineurl||!$ninesecret) {
$this->writeln("Synchronisation impossible soit parametres NINE_URL et/ou NINE_SECRET manquant");
return Command::FAILURE;
}
$nineurl.="/rest/";
$this->writeln('');
$this->writeln('=====================================================');
$this->writeln('== SYNCHONISATION NINE TO NINE ======================');
$this->writeln('=====================================================');
$nineniveau01s=$this->em->createQueryBuilder()->select('entity')->from('App:Niveau01','entity')->where('entity.idexternal IS NOT NULL')->getQuery()->getResult();
$ninegroups=$this->em->createQueryBuilder()->select('entity')->from('App:Group','entity')->where('entity.idexternal IS NOT NULL')->getQuery()->getResult();
$tbniveau01members=[];
$tbgroupmembers=[];
$tbniveau01s=[];
$tbgroups=[];
$tbusers=[];
$fgsynchropurgeniveau01s=($this->synchropurgeniveau01);
$fgsynchropurgegroups=($this->synchropurgegroup);
$fgsynchropurgeusers=($this->synchropurgeuser);
$this->writeln('');
$this->writeln('== NIVEAU01 =========================================');
$response = $this->apiservice->run("GET",$nineurl."getAllNiveau01s",null,["key"=>$ninesecret]);
if($response->code!="200") return Command::FAILURE;
foreach($response->body as $nineniveau01 ) {
$niveau01other=$this->em->getRepository("App\Entity\Niveau01")->findOneBy(["label"=>$nineniveau01->niveau01label]);
if($niveau01other&&$niveau01other->getIdexternal()!=$nineniveau01->niveau01id) {
$this->writelnred(" > ".$nineniveau01->niveau01label." = Impossible à synchroniser un autre niveau01 existe déjà avec ce label");
continue;
}
// On recherche le groupe via le gid
$this->writeln(' > '.$nineniveau01->niveau01label);
$niveau01=$this->em->getRepository("App\Entity\Niveau01")->findOneBy(["idexternal"=>$nineniveau01->niveau01id]);
if(!$niveau01) {
$niveau01=new Niveau01();
$niveau01->setApikey(Uuid::uuid4());
$this->em->persist($niveau01);
}
$niveau01->setIdexternal($nineniveau01->niveau01id);
$niveau01->setLabel($nineniveau01->niveau01label);
$this->em->flush();
// Sauvegarde du niveau01nine
array_push($tbniveau01s,$nineniveau01->niveau01label);
// Sauvegarde des membres du niveau01
if(!empty($nineniveau01->niveau01users)) {
foreach($nineniveau01->niveau01users as $member) {
if(!array_key_exists($member->userlogin,$tbniveau01members)) $tbniveau01members[$member->userlogin]=[];
array_push($tbniveau01members[$member->userlogin],$nineniveau01->niveau01label);
}
}
}
$this->writeln('');
$this->writeln('== GROUP ============================================');
$response = $this->apiservice->run("GET",$nineurl."getAllGroups",null,["key"=>$ninesecret]);
if($response->code!="200") return Command::FAILURE;
foreach($response->body as $ninegroup ) {
$groupother=$this->em->getRepository("App\Entity\Group")->findOneBy(["label"=>$ninegroup->grouplabel]);
if($groupother&&$groupother->getIdexternal()!=$ninegroup->groupid) {
$this->writelnred(" > ".$ninegroup->grouplabel." = Impossible à synchroniser un autre group existe déjà avec ce label");
continue;
}
// On recherche le groupe via le gid
$this->writeln(' > '.$ninegroup->grouplabel);
$group=$this->em->getRepository("App\Entity\Group")->findOneBy(["idexternal"=>$ninegroup->groupid]);
if(!$group) {
$group=new Group();
$group->setIsopen(false);
$group->setIsworkgroup(false);
$group->setApikey(Uuid::uuid4());
$this->em->persist($group);
}
$group->setIdexternal($ninegroup->groupid);
$group->setLabel($ninegroup->grouplabel);
$this->em->flush();
// Sauvegarde du groupnine
array_push($tbgroups,$ninegroup->grouplabel);
// Sauvegarde des membres du group
if(!empty($ninegroup->groupusers)) {
foreach($ninegroup->groupusers as $member) {
if(!array_key_exists($member->userlogin,$tbgroupmembers)) $tbgroupmembers[$member->userlogin]=[];
array_push($tbgroupmembers[$member->userlogin],$ninegroup->grouplabel);
}
}
}
$this->writeln('');
$this->writeln('== USER =============================================');
$response = $this->apiservice->run("GET",$nineurl."getAllUsers",null,["key"=>$ninesecret]);
if($response->code!="200") return Command::FAILURE;
$nineusers=$response->body;
foreach($nineusers as $nineuser) {
$userother=$this->em->getRepository("App\Entity\User")->findOneBy(["email"=>$nineuser->useremail]);
if($userother&&$userother->getUsername()!=$nineuser->userlogin) {
$this->writelnred(" > ".$nineuser->userlogin." = Impossible à synchroniser un autre user existe déjà avec ce mail");
continue;
}
$userother=$this->em->getRepository("App\Entity\Registration")->findOneBy(["email"=>$nineuser->useremail]);
if($userother&&$userother->getUSername()!=$nineuser->userlogin) {
$this->writelnred(" > ".$nineuser->userlogin." = Impossible à synchroniser un autre user existe déjà avec ce mail");
continue;
}
// On recherche le user via le username
$this->writeln(' > '.$nineuser->userlogin);
$user=$this->em->getRepository("App\Entity\User")->findOneBy(["username"=>$nineuser->userlogin]);
if(!$user) {
$user=new User();
$user->setUsername($nineuser->userlogin);
$user->setIsvisible(true);
$user->setApikey(Uuid::uuid4());
$user->setPassword("NINEPWD-".$nineuser->userlogin);
$user->setRole("ROLE_USER");
$user->setAvatar($nineuser->useravatar);
$this->em->persist($user);
}
// Recherche du niveau01
$niveau01=null;
if($user->getNiveau01()&&empty($user->getNiveau01()->getIdexternal()))
$niveau01=$user->getNiveau01();
if(array_key_exists($nineuser->userlogin,$tbniveau01members))
$niveau01=$this->em->getRepository("App\Entity\Niveau01")->findOneBy(["label"=>$tbniveau01members[$nineuser->userlogin][0]]);
if(!$niveau01)
$niveau01=$this->em->getRepository('App\Entity\Niveau01')->find(-1);
// Mise à jour des attributs
if(!empty($nineuser->userlastname)) $user->setLastname($nineuser->userlastname);
if(!empty($nineuser->userfirstname)) $user->setFirstname($nineuser->userfirstname);
if(!empty($nineuser->useremail)) $user->setEmail($nineuser->useremail);
if(!empty($nineuser->useravatar)) $user->setAvatar($nineuser->useravatar);
// Mise à jour du niveau01
if($niveau01!=$user->getNiveau01()) $user->setNiveau02(null);
$user->setNiveau01($niveau01);
// Mise à jour du role
if(in_array($nineuser->userlogin,$this->container->getParameter("appAdmins")))
$user->setRole("ROLE_ADMIN");
// Sauvegarde en bdd
$this->em->flush();
// Sauvegarde du userldap
array_push($tbusers,$nineuser->userlogin);
// Inscription au groupe
if(array_key_exists($nineuser->userlogin,$tbgroupmembers)) {
foreach($tbgroupmembers[$nineuser->userlogin] as $grouplabel) {
$group=$this->em->getRepository("App\Entity\Group")->findOneBy(["label"=>$grouplabel]);
if($group) {
$usergroup=$this->em->getRepository("App\Entity\UserGroup")->findOneBy(["user"=>$user,"group"=>$group]);
if(!$usergroup) {
$usergroup=new UserGroup();
$usergroup->setUser($user);
$usergroup->setGroup($group);
$usergroup->setApikey(Uuid::uuid4());
$usergroup->setRolegroup(0);
$this->em->persist($usergroup);
$this->em->flush();
}
}
}
}
// Desinscription des group ldap
foreach($ninegroups as $group) {
if(!array_key_exists($nineuser->userlogin,$tbgroupmembers)||!in_array($group->getLabel(),$tbgroupmembers[$nineuser->userlogin])) {
$usergroup=$this->em->getRepository("App\Entity\UserGroup")->findOneBy(["user"=>$user,"group"=>$group]);
if($usergroup) {
$this->em->remove($usergroup);
$this->em->flush();
}
}
}
}
// Purge des users
if($fgsynchropurgeusers) {
$this->writeln('');
$this->writeln('== PURGE USER =============================================');
$users=$this->em->getRepository("App\Entity\User")->findAll();
foreach($users as $user) {
if(!in_array($user->getUsername(),$tbusers)) {
if($user->getId()>0) {
$this->writeln(' > '.$user->getUsername());
$this->em->remove($user);
$this->em->flush();
}
}
}
}
// Purge des groups
if($fgsynchropurgegroups) {
$this->writeln('');
$this->writeln('== PURGE GROUP =============================================');
foreach($ninegroups as $group) {
if(!in_array($group->getLabel(),$tbgroups)) {
if($group->getId()>0) {
$this->writeln(' > '.$group->getLabel());
$this->em->remove($group);
}
else {
$group->setLdapfilter(null);
$group->setIdexternal(null);
}
$this->em->flush();
}
}
}
// Purge des niveau01s
if($fgsynchropurgeniveau01s) {
$this->writeln('');
$this->writeln('== PURGE NIVEAU01 =============================================');
foreach($nineniveau01s as $niveau01) {
if(!in_array($niveau01->getLabel(),$tbniveau01s)) {
if($niveau01->getId()>0) {
$user=$this->em->getRepository("App\Entity\User")->findOneBy(["niveau01"=>$niveau01]);
if($user) {
$resetniveau01=$this->em->getRepository("App\Entity\User")->find(-1);
$user->setNiveau01($resetniveau01);
$user->setNiveau02(null);
}
$this->writeln(' > '.$niveau01->getLabel());
$this->em->remove($niveau01);
}
else {
$niveau01->setLdapfilter(null);
$niveau01->setIdexternal(null);
}
$this->em->flush();
}
}
}
return Command::SUCCESS;
}
private function writelnred($string) {
$this->output->writeln('<fg=red>'.$string.'</>');
$this->filesystem->appendToFile($this->rootlog.'cron.log', $string."\n");
}
private function writeln($string) {
$this->output->writeln($string);
$this->filesystem->appendToFile($this->rootlog.'cron.log', $string."\n");
}
protected function addUser($niveau01,$username,$firstname,$lastname,$email,$usersadmin) {
$user = new User();
$user->setUsername($username);
$user->setLastname($lastname);
$user->setFirstname($firstname);
$user->setEmail($email);
$user->setNiveau01($niveau01);
$user->setSiren($niveau01->getSiren());
$user->setPassword("PASSWORDFROMEXTERNE");
$user->setVisible(true);
$user->setAuthlevel("simple");
$user->setBelongingpopulation("agent");
if(in_array($username,$usersadmin))
$user->setRole("ROLE_ADMIN");
else {
$user->setRole("ROLE_USER");
// Si modèle scribe
$ldap_template = $this->container->getParameter('ldap_template');
if($ldap_template=="scribe") {
$ldapfilter="(|(&(uid=".$user->getUsername().")(ENTPersonProfils=enseignant))(&(uid=".$user->getUsername().")(typeadmin=0))(&(uid=".$user->getUsername().")(typeadmin=2)))";
$results = $this->ldap->search($ldapfilter, ['uid'], $this->ldap_basedn);
if($results) $user->setRole("ROLE_ANIM");
}
}
$this->em->persist($user);
$this->em->flush();
}
protected function modUser($user,$username,$firstname,$lastname,$email,$usersadmin) {
$user->setLastname($lastname);
$user->setFirstname($firstname);
$user->setEmail($email);
if(in_array($username,$usersadmin))
$user->setRole("ROLE_ADMIN");
$this->em->persist($user);
$this->em->flush();
}
}

0
src/Controller/.gitignore vendored Normal file
View File

View File

@ -0,0 +1,85 @@
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Doctrine\Persistence\ManagerRegistry;
use App\Entity\Config as Entity;
use App\Form\ConfigType as Form;
class ConfigController extends AbstractController
{
private $data="config";
private $entity="App\Entity\Config";
private $twig="Config/";
private $route="app_admin_config";
public function list($access): Response
{
return $this->render($this->twig.'list.html.twig',[
"useheader"=>true,
"usemenu"=>false,
"usesidebar"=>true,
]);
}
public function listrender($access,$category,ManagerRegistry $em): Response
{
$datas = $em->getRepository($this->entity)->findBy(["visible"=>true,"category"=>$category]);
return $this->render($this->twig.'render.html.twig',[
$this->data."s" => $datas,
]);
}
public function update($access,$id,Request $request,ManagerRegistry $em): Response
{
// Initialisation de l'enregistrement
$data=$em->getRepository($this->entity)->find($id);
if(!$data->getValue())
$data->setValue($request->getSession()->get($data->getId()));
// Création du formulaire
$form = $this->createForm(Form::class,$data,array("mode"=>"update","id"=>$data->getId(),"type"=>$data->getType(),"required"=>$data->isRequired()));
// Récupération des data du formulaire
$form->handleRequest($request);
// Sur validation
if ($form->get('submit')->isClicked() && $form->isValid()) {
$data = $form->getData();
$em->getManager()->flush();
// Retour à la liste
return $this->redirectToRoute($this->route);
}
// Affichage du formulaire
return $this->render($this->twig.'edit.html.twig', [
'useheader' => true,
'usemenu' => false,
'usesidebar' => true,
$this->data => $data,
'mode' => 'update',
'form' => $form->createView()
]);
}
public function delete($access,$id,Request $request,ManagerRegistry $em): Response
{
// Récupération de l'enregistrement courant
$config=$em->getRepository($this->entity)->find($id);
if(!$config->isRequired()) {
$config->setValue("");
$em->getManager()->flush();
}
return $this->redirectToRoute($this->route);
}
public function logo($access): Response
{
return $this->render($this->twig.'logo.html.twig');
}
}

View File

@ -0,0 +1,184 @@
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use App\Form\CronType as Form;
class CronController extends AbstractController
{
private $data="cron";
private $entity="App\Entity\Cron";
private $twig="Cron/";
private $route="app_admin_cron";
public function list(): Response
{
return $this->render($this->twig.'list.html.twig',[
"useheader"=>true,
"usemenu"=>false,
"usesidebar"=>true,
]);
}
public function tablelist(Request $request,ManagerRegistry $em): Response
{
$query=$request->query->all();
$start=$query['start'];
$length=$query['length'];
$search=$query['search'];
$draw= $query['draw'];
$ordercolumn=$query['order'][0]['column'];
$orderdir=$query['order'][0]['dir'];
// Nombre total d'enregistrement
$total = $em->getManager()->createQueryBuilder()->select('COUNT(entity)')->from($this->entity,'entity')->getQuery()->getSingleScalarResult();
// Nombre d'enregistrement filtré
if(!$search||$search["value"]=="")
$totalf = $total;
else {
$totalf= $em->getManager()->createQueryBuilder()
->select('COUNT(entity)')
->from($this->entity,'entity')
->where('entity.command LIKE :value OR entity.description LIKE :value')
->setParameter("value", "%".$search["value"]."%")
->getQuery()
->getSingleScalarResult();
}
// Construction du tableau de retour
$output = array(
'draw' => $draw,
'recordsFiltered' => $totalf,
'recordsTotal' => $total,
'data' => array(),
);
// Parcours des Enregistrement
$qb = $em->getManager()->createQueryBuilder();
$qb->select('entity')->from($this->entity,'entity');
if($search&&$search["value"]!="") {
$qb ->andWhere('entity.command LIKE :value OR entity.description LIKE :value')
->setParameter("value", "%".$search["value"]."%");
}
if($ordercolumn) {
switch($ordercolumn) {
case 1 :
$qb->orderBy('entity.nextexecdate',$orderdir);
break;
case 2 :
$qb->orderBy('entity.command',$orderdir);
break;
}
}
$datas=$qb->setFirstResult($start)->setMaxResults($length)->getQuery()->getResult();
foreach($datas as $data) {
// Action
$action = "";
$action.="<a href='".$this->generateUrl($this->route.'_update', array('id'=>$data->getId()))."'><i class='fa fa-file fa-fw fa-2x'></i></a>";
$tmp=array();
array_push($tmp,$action);
array_push($tmp,$data->getNextexecdate()->format("d/m/Y H:i"));
array_push($tmp,$data->getCommand());
array_push($tmp,$data->getDescription());
array_push($tmp,$data->getStatutLabel());
array_push($output["data"],$tmp);
}
// Retour
return new JsonResponse($output);
}
public function update($id,Request $request,ManagerRegistry $em): Response
{
// Initialisation de l'enregistrement
$data=$em->getRepository($this->entity)->find($id);
if (!$data) throw $this->createNotFoundException('Unable to find entity.');
// Création du formulaire
$form = $this->createForm(Form::class,$data,array(
"mode"=>"update",
));
// Récupération des data du formulaire
$form->handleRequest($request);
// Sur validation
if ($form->get('submit')->isClicked() && $form->isValid()) {
$data = $form->getData();
$em->getManager()->flush();
// Retour à la liste
return $this->redirectToRoute($this->route);
}
// Affichage du formulaire
return $this->render($this->twig.'edit.html.twig', [
'useheader' => true,
'usemenu' => false,
'usesidebar' => true,
$this->data => $data,
'mode' => 'update',
'form' => $form->createView()
]);
}
public function log()
{
return $this->render($this->render.'logs.html.twig', [
'useheader' => true,
'usesidebar' => true,
]);
}
public function getlog(Request $request, $id)
{
$path = $this->getParameter('kernel.project_dir');
if($id=="dump")
$file = $path . '/var/log/' . $this->getParameter("appAlias") . '.sql';
else
$file = $path . '/var/log/'.$id.'.log';
$fs = new Filesystem();
if($fs->exists($file)) {
$response = new BinaryFileResponse($file);
$response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT);
return $response;
}
else return $this->redirectToRoute($this->route."_log");
}
protected function getErrorForm($id,$form,$request,$data,$mode) {
if ($form->get('submit')->isClicked()&&$mode=="delete") {
}
if ($form->get('submit')->isClicked() && $mode=="submit") {
}
if ($form->get('submit')->isClicked() && !$form->isValid()) {
$this->get('session')->getFlashBag()->clear();
$errors = $form->getErrors();
foreach( $errors as $error ) {
$request->getSession()->getFlashBag()->add("error", $error->getMessage());
}
}
}
}

View File

@ -0,0 +1,244 @@
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\HttpFoundation\Response;
class CropController extends AbstractController
{
private $appKernel;
public function __construct(KernelInterface $appKernel)
{
$this->appKernel = $appKernel;
}
// Etape 01 - Téléchargement de l'image
public function crop01($type,$reportinput): Response
{
return $this->render('Crop/crop01.html.twig',[
'useheader' => false,
'usesidebar' => false,
'type' => $type,
'reportinput' => $reportinput
]);
}
// Etape 02 - Couper votre l'image
public function crop02($type,$reportinput,Request $request)
{
// Récupération de l'image à cropper
$file=$request->query->get('file');
$large_image_location = "uploads/$type/$file";
// Récupérer les tailles de l'image
$width = $this->getWidth($large_image_location);
$height = $this->getHeight($large_image_location);
// Définir le pourcentage de réduction de l'image
switch ($type) {
case "illustration":
$max_height=0;
$ratio="1:1";
break;
case "avatar":
$max_height=900;
$max_width=900;
$ratio="1:1";
break;
case "header":
$max_height=1600;
$max_width=1600;
$ratio="16:2";
break;
case "hero":
$max_height=1600;
$max_width=1600;
$ratio="16:9";
break;
case "image":
$max_height=1600;
$max_width=1600;
$ratio="1:1";
break;
}
if($max_height>0) {
$scale = $max_height/$height;
if(($width*$scale)>$max_width) {
$scale = $max_width/$width;
}
$this->resizeImage($large_image_location,$width,$height,$scale);
}
else $scale=1;
// Construction du formulaire
$submited=false;
$form = $this->createFormBuilder()
->add('submit',SubmitType::class,array("label" => "Valider","attr" => array("class" => "btn btn-success")))
->add('x',HiddenType::class)
->add('y',HiddenType::class)
->add('w',HiddenType::class)
->add('h',HiddenType::class)
->add('xs',HiddenType::class)
->add('ys',HiddenType::class)
->add('ws',HiddenType::class)
->add('hs',HiddenType::class)
->getForm();
// Récupération des data du formulaire
$form->handleRequest($request);
// Sur validation on généère la miniature croppée
if ($form->get('submit')->isClicked() && $form->isValid()) {
// Récupération des valeurs du formulaire
$data = $form->getData();
$thumb_image_location = "uploads/$type/thumb_".$file;
$cropped = $this->resizeThumbnailImage($thumb_image_location, $large_image_location,$data["ws"],$data["hs"],$data["xs"],$data["ys"],$scale);
$submited=true;
}
return $this->render('Crop/crop02.html.twig', [
'useheader' => false,
'usesidebar' => false,
'form' => $form->createView(),
'type' => $type,
'file' => $file,
'ratio' => $ratio,
"reportinput" => $reportinput,
"submited" => $submited
]);
}
// Upload ckeditor
public function ckupload(Request $request) {
// Fichier temporaire uploadé
$tmpfile = $request->files->get('upload');
$extention = $tmpfile->getClientOriginalExtension();
// Répertoire de Destination
$fs = new Filesystem();
$rootdir = $this->appKernel->getProjectDir()."/public";
$fs->mkdir($rootdir."/uploads/ckeditor");
// Fichier cible
$targetName = uniqid().".".$extention;
$targetFile = $rootdir."/uploads/ckeditor/".$targetName;
$targetUrl = "/".$this->getParameter('appAlias')."/uploads/ckeditor/".$targetName;
$message = "";
move_uploaded_file($tmpfile,$targetFile);
$output["uploaded"]=1;
$output["fileName"]=$targetName;
$output["url"]=$targetUrl;
return new Response(json_encode($output));
}
// Calcul de la hauteur
protected function getHeight($image) {
$size = getimagesize($image);
$height = $size[1];
return $height;
}
// Cacul de la largeur
protected function getWidth($image) {
$size = getimagesize($image);
$width = $size[0];
return $width;
}
protected function resizeImage($image,$width,$height,$scale) {
list($imagewidth, $imageheight, $imageType) = getimagesize($image);
$imageType = image_type_to_mime_type($imageType);
$newImageWidth = ceil($width * $scale);
$newImageHeight = ceil($height * $scale);
$newImage = imagecreatetruecolor($newImageWidth,$newImageHeight);
switch($imageType) {
case "image/gif":
$source=imagecreatefromgif($image);
break;
case "image/pjpeg":
case "image/jpeg":
case "image/jpg":
$source=imagecreatefromjpeg($image);
break;
case "image/png":
case "image/x-png":
$source=imagecreatefrompng($image);
break;
}
imagecopyresampled($newImage,$source,0,0,0,0,$newImageWidth,$newImageHeight,$width,$height);
switch($imageType) {
case "image/gif":
imagegif($newImage,$image);
break;
case "image/pjpeg":
case "image/jpeg":
case "image/jpg":
imagejpeg($newImage,$image,90);
break;
case "image/png":
case "image/x-png":
imagepng($newImage,$image);
break;
}
chmod($image, 0640);
return $image;
}
protected function resizeThumbnailImage($thumb_image_name, $image, $width, $height, $start_width, $start_height, $scale){
$fs = new Filesystem();
$fs->remove($thumb_image_name);
list($imagewidth, $imageheight, $imageType) = getimagesize($image);
$imageType = image_type_to_mime_type($imageType);
$newImageWidth = ceil($width * $scale);
$newImageHeight = ceil($height * $scale);
$newImage = imagecreatetruecolor($newImageWidth,$newImageHeight);
switch($imageType) {
case "image/gif":
$source=imagecreatefromgif($image);
break;
case "image/pjpeg":
case "image/jpeg":
case "image/jpg":
$source=imagecreatefromjpeg($image);
break;
case "image/png":
case "image/x-png":
$source=imagecreatefrompng($image);
break;
}
imagecopyresampled($newImage,$source,0,0,$start_width,$start_height,$newImageWidth,$newImageHeight,$width,$height);
switch($imageType) {
case "image/gif":
imagegif($newImage,$thumb_image_name);
break;
case "image/pjpeg":
case "image/jpeg":
case "image/jpg":
imagejpeg($newImage,$thumb_image_name,90);
break;
case "image/png":
case "image/x-png":
imagepng($newImage,$thumb_image_name);
break;
}
chmod($thumb_image_name, 0640);
return $thumb_image_name;
}
}

View File

@ -0,0 +1,827 @@
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Doctrine\Persistence\ManagerRegistry;
use Ramsey\Uuid\Uuid;
use App\Entity\Group as Entity;
use App\Entity\UserGroup;
use App\Form\GroupType as Form;
class GroupController extends AbstractController
{
private $data="group";
private $entity="App\Entity\Group";
private $twig="Group/";
private $route="app_admin_group";
public function list($access): Response
{
return $this->render($this->twig.'list.html.twig',[
"useheader"=>true,
"usemenu"=>false,
"usesidebar"=>($access!="user"),
"access"=>$access,
]);
}
public function tablelist($access,Request $request,ManagerRegistry $em): Response
{
$query=$request->query->all();
$start=$query['start'];
$length=$query['length'];
$search=$query['search'];
$draw= $query['draw'];
$ordercolumn=$query['order'][0]['column'];
$orderdir=$query['order'][0]['dir'];
$user=$this->getUser();
// Nombre total d'enregistrement
$qb = $em->getManager()->createQueryBuilder();
$qb->select('COUNT(entity)')->from($this->entity,'entity')->getQuery()->getSingleScalarResult();
if($access=="user") {
$qb ->from("App:UserGroup","usergroup")
->andWhere(("entity.isworkgroup=:flag"))
->andWhere("entity.id=usergroup.group")
->andWhere("usergroup.user=:user")
->setParameter("flag", true)
->setParameter("user", $user);
}
$total = $qb->getQuery()->getSingleScalarResult();
// Nombre d'enregistrement filtré
if(!$search||$search["value"]=="")
$totalf = $total;
else {
$qb= $em->getManager()->createQueryBuilder();
$qb ->select('COUNT(entity)')
->from($this->entity,'entity')
->where('entity.label LIKE :value')
->leftJoin('App:User', 'user','WITH','entity.owner = user.id AND user.username LIKE :value')
->setParameter("value", "%".$search["value"]."%")
->getQuery()
->getSingleScalarResult();
if($access=="user") {
$qb ->from("App:UserGroup","usergroup")
->andWhere(("entity.isworkgroup=:flag"))
->andWhere("entity.id=usergroup.group")
->andWhere("usergroup.user=:user")
->setParameter("flag", true)
->setParameter("user", $user);
}
$totalf= $qb->getQuery()->getSingleScalarResult();
}
// Construction du tableau de retour
$output = array(
'draw' => $draw,
'recordsFiltered' => $totalf,
'recordsTotal' => $total,
'data' => array(),
);
// Parcours des Enregistrement
$qb = $em->getManager()->createQueryBuilder();
$qb ->select('entity')
->from($this->entity,'entity');
if($access=="user") {
$qb ->from("App:UserGroup","usergroup")
->andWhere(("entity.isworkgroup=:flag"))
->andWhere("entity.id=usergroup.group")
->andWhere("usergroup.user=:user")
->setParameter("flag", true)
->setParameter("user", $user);
}
if($search&&$search["value"]!="") {
$qb ->andWhere('entity.label LIKE :value')
->setParameter("value", "%".$search["value"]."%");
}
if($ordercolumn) {
switch($ordercolumn) {
case 1 :
$qb->orderBy('entity.label',$orderdir);
break;
case 2 :
$qb->orderBy('entity.isworkgroup',$orderdir);
break;
case 3 :
$qb->orderBy('entity.isopen',$orderdir);
break;
case 4 :
$qb->orderBy('entity.owner',$orderdir);
break;
}
}
$datas=$qb->setFirstResult($start)->setMaxResults($length)->getQuery()->getResult();
foreach($datas as $data) {
// Action
$action = "";
switch($access) {
case "admin":
if($this->canupdate($access,$data,$em,false))
$action.="<a href='".$this->generateUrl(str_replace("_admin_","_".$access."_",$this->route).'_update', ['id'=>$data->getId()])."'><i class='fa fa-file fa-fw fa-2x'></i></a>";
if($this->canseemember($access,$data,$em,false))
$action.="<a href='".$this->generateUrl(str_replace("_admin_","_".$access."_",$this->route).'_users', ['id'=>$data->getId()])."'><i class='fa fa-users fa-fw fa-2x'></i></a>";
break;
case "modo":
if($this->canupdate($access,$data,$em,false))
$action.="<a href='".$this->generateUrl(str_replace("_admin_","_".$access."_",$this->route).'_update', ['id'=>$data->getId()])."'><i class='fa fa-file fa-fw fa-2x'></i></a>";
if($this->canseemember($access,$data,$em,false))
$action.="<a href='".$this->generateUrl(str_replace("_admin_","_".$access."_",$this->route).'_users', ['id'=>$data->getId()])."'><i class='fa fa-users fa-fw fa-2x'></i></a>";
break;
case "user":
if($this->canupdate($access,$data,$em,false))
$action.="<a href='".$this->generateUrl(str_replace("_admin_","_".$access."_",$this->route).'_update', ['id'=>$data->getId()])."'><i class='fa fa-file fa-fw fa-2x'></i></a>";
if($this->canseemember($access,$data,$em,false))
$action.="<a href='".$this->generateUrl(str_replace("_admin_","_".$access."_",$this->route).'_users', ['id'=>$data->getId()])."'><i class='fa fa-users fa-fw fa-2x'></i></a>";
// On ne peut se désinscrire que si le groupe est ouvert et qu'il n'est pas lié à un groupe ldap ou sso
if($data->getOwner()!=$this->getUser()&&($data->isIsOpen()||$this->canupdatemember($access,$data,$em,false)))
$action.="<a href='".$this->generateUrl(str_replace("_admin_","_".$access."_",$this->route).'_userout', ['id'=>$data->getId()])."'><i class='fa fa-sign-out-alt fa-fw fa-2x'></i></a>";
break;
}
$userinfo="";
if($data->getOwner()) {
if(stripos($data->getOwner()->getAvatar(),"http")===0)
$userinfo.="<img src='".$data->getOwner()->getAvatar()."' class='avatar'>";
else
$userinfo.="<img src='".$this->getParameter('appAlias')."uploads/avatar/".$data->getOwner()->getAvatar()."' class='avatar'>";
$userinfo.="<br>".$data->getOwner()->getUsername();
}
$visitecpt=0;
$visitelast=null;
foreach($data->getUsers() as $usergroup) {
$visitecpt+=intval($usergroup->getVisitecpt());
$visitelast=($usergroup->getVisitedate()>$visitelast?$usergroup->getVisitedate():$visitelast);
}
$tmp=array();
array_push($tmp,$action);
array_push($tmp,$data->getLabel());
array_push($tmp,($data->isIsworkgroup()?"oui":"non"));
array_push($tmp,($data->isIsopen()?"oui":"non"));
array_push($tmp,$userinfo);
array_push($tmp,($visitelast?$visitelast->format("d/m/Y H:i")."<br>":"")."nb = ".$visitecpt);
array_push($output["data"],$tmp);
}
// Retour
return new JsonResponse($output);
}
public function submit($access,Request $request,ManagerRegistry $em): Response
{
// Initialisation de l'enregistrement
$data = new Entity();
$data->setApikey(Uuid::uuid4());
if($access=="user") {
$data->setOwner($this->getUser());
$data->setIsworkgroup(true);
}
// Controler les permissions
$this->cansubmit($access,$em);
// Création du formulaire
$form = $this->createForm(Form::class,$data,array(
"mode"=>"submit",
"appMasteridentity"=>$this->GetParameter("appMasteridentity"),
"access"=>$access,
));
// Récupération des data du formulaire
$form->handleRequest($request);
// Sur validation
if ($form->get('submit')->isClicked() && $form->isValid()) {
$data = $form->getData();
// Les groupes opé ne sont pas ouvert
if(!$data->isIsworkgroup()) $data->setIsopen(false);
// Sauvegarde
$em->getManager()->persist($data);
$em->getManager()->flush();
// Retour à la liste
return $this->redirectToRoute(str_replace("_admin_","_".$access."_",$this->route));
}
// Affichage du formulaire
return $this->render($this->twig.'edit.html.twig', [
"useheader"=>true,
"usemenu"=>false,
"usesidebar"=>($access!="user"),
"mode"=>"submit",
"access"=>$access,
"form"=>$form->createView(),
$this->data=>$data,
"maxsize"=>($access=="user"?1200:null),
]);
}
public function update($id,$access,Request $request,ManagerRegistry $em): Response
{
// Initialisation de l'enregistrement
$data=$em->getRepository($this->entity)->find($id);
if (!$data or $id<0) throw $this->createNotFoundException('Unable to find entity.');
// Controler les permissions
$this->canupdate($access,$data,$em);
// Création du formulaire
$form = $this->createForm(Form::class,$data,array(
"mode"=>"update",
"appMasteridentity"=>$this->GetParameter("appMasteridentity"),
"access"=>$access,
));
// Récupération des data du formulaire
$form->handleRequest($request);
// Sur validation
if ($form->get('submit')->isClicked() && $form->isValid()) {
$data = $form->getData();
// Les groupes opé ne sont pas ouvert
if(!$data->isIsworkgroup()) $data->setIsopen(false);
$em->getManager()->flush();
// Retour à la liste
return $this->redirectToRoute(str_replace("_admin_","_".$access."_",$this->route));
}
// Affichage du formulaire
return $this->render($this->twig.'edit.html.twig', [
"useheader" => true,
"usemenu" => false,
"usesidebar" => ($access!="user"),
$this->data => $data,
"mode" => "update",
"access"=>$access,
"form" => $form->createView(),
"maxsize"=>($access=="user"?1200:null),
]);
}
public function delete($id,$access,Request $request,ManagerRegistry $em): Response
{
// Récupération de l'enregistrement courant
$data=$em->getRepository($this->entity)->find($id);
if (!$data) throw $this->createNotFoundException('Unable to find entity.');
// Controler les permissions
$this->canupdate($access,$data,$em);
// Tentative de suppression
try{
$em->getManager()->remove($data);
$em->getManager()->flush();
}
catch (\Exception $e) {
$request->getSession()->getFlashBag()->add("error", $e->getMessage());
return $this->redirectToRoute(str_replace("_admin_","_".$access."_",$this->route)."_update",["id"=>$id]);
}
return $this->redirectToRoute(str_replace("_admin_","_".$access."_",$this->route));
}
public function users($id,$access,Request $request,ManagerRegistry $em)
{
// Récupération de l'enregistrement courant
$data=$em->getRepository($this->entity)->find($id);
if (!$data) throw $this->createNotFoundException('Unable to find entity.');
// Controler les permissions
$this->canseemember($access,$data,$em);
// Affichage du formulaire
return $this->render($this->twig.'users.html.twig', [
'useheader' => true,
'usemenu' => false,
'usesidebar' => ($access!="user"),
'access' => $access,
$this->data => $data,
]);
}
public function usersnotin($id,$access,Request $request,ManagerRegistry $em)
{
// Récupération de l'enregistrement courant
$group=$em->getRepository($this->entity)->find($id);
if (!$group) throw $this->createNotFoundException('Unable to find entity.');
// Controler les permissions
$this->canseemember($access,$group,$em);
$sub = $em->getManager()->createQueryBuilder();
$sub->select("usergroup");
$sub->from("App:UserGroup","usergroup");
$sub->andWhere('usergroup.user = user.id');
$sub->andWhere('usergroup.group = :groupid');
$query=$request->query->all();
$start=$query['start'];
$length=$query['length'];
$search=$query['search'];
$draw= $query['draw'];
$ordercolumn=$query['order'][0]['column'];
$orderdir=$query['order'][0]['dir'];
// Nombre total d'enregistrement
$qb = $em->getManager()->createQueryBuilder();
switch($access) {
case "admin":
$qb->select('COUNT(user)')
->from('App:User','user')
->where($qb->expr()->not($qb->expr()->exists($sub->getDQL())))
->setParameter("groupid",$id);
break;
case "modo":
$usermodo=$this->getUser()->getId();
$qb->select('COUNT(user)')
->from('App:User','user')
->from('App:UserModo','usermodo')
->where($qb->expr()->not($qb->expr()->exists($sub->getDQL())))
->andWhere("usermodo.niveau01 = user.niveau01")
->andWhere("usermodo.user = :userid")
->setParameter("userid", $usermodo)
->setParameter("groupid",$id);
break;
case "user":
$niveau01=$this->getUser()->getNiveau01();
$niveau02=$this->getUser()->getNiveau02();
$qb->select('COUNT(user)')
->from('App:User','user')
->where($qb->expr()->not($qb->expr()->exists($sub->getDQL())))
->setParameter("groupid",$id);
switch($request->getSession()->get("scopeannu")) {
case "SAME_NIVEAU01":
$qb->andWhere("user.niveau01 = :niveau01")->setParameter("niveau01",$niveau01);
break;
case "SAME_NIVEAU02":
$qb->andWhere("user.niveau02 = :niveau02")->setParameter("niveau02",$niveau02);
break;
}
break;
}
$total=$qb->getQuery()->getSingleScalarResult();
// Nombre d'enregistrement filtré
if($search["value"]=="")
$totalf = $total;
else {
switch($access) {
case "admin":
$totalf= $em->getManager()->createQueryBuilder()
->select('COUNT(user)')
->from('App:User','user')
->where('user.username LIKE :value OR user.email LIKE :value')
->andWhere($qb->expr()->not($qb->expr()->exists($sub->getDQL())))
->setParameter("value", "%".$search["value"]."%")
->setParameter("groupid",$id)
->getQuery()
->getSingleScalarResult();
break;
case "modo":
$totalf = $em->getManager()->createQueryBuilder()
->select('COUNT(user)')
->from('App:User','user')
->from('App:UserModo','usermodo')
->where('user.username LIKE :value OR user.email LIKE :value')
->andWhere($qb->expr()->not($qb->expr()->exists($sub->getDQL())))
->andWhere("usermodo.niveau01 = user.niveau01")
->andWhere("usermodo.user = :userid")
->setParameter("userid", $usermodo)
->setParameter("value", "%".$search["value"]."%")
->setParameter("groupid",$id)
->getQuery()
->getSingleScalarResult();
break;
case "user":
$qb = $em->getManager()->createQueryBuilder()
->select('COUNT(user)')
->from('App:User','user')
->where('user.username LIKE :value OR user.email LIKE :value')
->andWhere($qb->expr()->not($qb->expr()->exists($sub->getDQL())))
->setParameter("value", "%".$search["value"]."%")
->setParameter("groupid",$id);
switch($request->getSession()->get("scopeannu")) {
case "SAME_NIVEAU01":
$qb->andWhere("user.niveau01 = :niveau01")->setParameter("niveau01",$niveau01);
break;
case "SAME_NIVEAU02":
$qb->andWhere("user.niveau02 = :niveau02")->setParameter("niveau02",$niveau02);
break;
}
$totalf=$qb->getQuery()->getSingleScalarResult();
break;
}
}
// Construction du tableau de retour
$output = array(
'draw' => $draw,
'recordsFiltered' => $totalf,
'recordsTotal' => $total,
'data' => array(),
);
// Parcours des Enregistrement
$qb = $em->getManager()->createQueryBuilder();
$qb->select('user')->from("App:User",'user');
switch($access) {
case "admin":
$qb->where($qb->expr()->not($qb->expr()->exists($sub->getDQL())));
break;
case "modo":
$qb->from('App:UserModo','usermodo')
->where($qb->expr()->not($qb->expr()->exists($sub->getDQL())))
->andWhere("usermodo.niveau01 = user.niveau01")
->andWhere("usermodo.user = :userid")
->setParameter("userid", $usermodo);
break;
case "user":
$qb->where($qb->expr()->not($qb->expr()->exists($sub->getDQL())));
switch($request->getSession()->get("scopeannu")) {
case "SAME_NIVEAU01":
$qb->andWhere("user.niveau01 = :niveau01")->setParameter("niveau01",$niveau01);
break;
case "SAME_NIVEAU02":
$qb->andWhere("user.niveau02 = :niveau02")->setParameter("niveau02",$niveau02);
break;
}
break;
}
if($search["value"]!="") {
$qb ->andWhere('user.username LIKE :value OR user.email LIKE :value')
->setParameter("value", "%".$search["value"]."%");
}
$qb->setParameter("groupid",$id);
switch($ordercolumn) {
case 2 :
$qb->orderBy('user.username',$orderdir);
break;
case 3 :
$qb->orderBy('user.email',$orderdir);
break;
}
$datas=$qb->setFirstResult($start)->setMaxResults($length)->getQuery()->getResult();
$canupdatemember=$this->canupdatemember($access,$group,$em,false);
foreach($datas as $data) {
// Action
$action = "";
if($canupdatemember)
$action.="<a style='cursor:pointer' onClick='addUsers(".$data->getId().")'><i class='fa fa-plus fa-fw'></i></a>";
// Avatar
if(stripos($data->getAvatar(),"http")===0)
$avatar="<img src='".$data->getAvatar()."' class='avatar'>";
else
$avatar="<img src='".$this->getParameter('appAlias')."uploads/avatar/".$data->getAvatar()."' class='avatar'>";
array_push($output["data"],array("DT_RowId"=>"user".$data->getId(),$action,$avatar,$data->getUsername(),$data->getEmail(),"",""));
}
// Retour
return new JsonResponse($output);
}
public function usersin($id,$access,Request $request,ManagerRegistry $em)
{
// Récupération de l'enregistrement courant
$group=$em->getRepository($this->entity)->find($id);
if (!$group) throw $this->createNotFoundException('Unable to find entity.');
// Controler les permissions
$this->canseemember($access,$group,$em);
$sub = $em->getManager()->createQueryBuilder();
$sub->select("usergroup");
$sub->from("App:UserGroup","usergroup");
$sub->andWhere('usergroup.user = user.id');
$sub->andWhere('usergroup.group = :groupid');
$query=$request->query->all();
$start=$query['start'];
$length=$query['length'];
$search=$query['search'];
$draw= $query['draw'];
$ordercolumn=$query['order'][0]['column'];
$orderdir=$query['order'][0]['dir'];
// Nombre total d'enregistrement
$qb = $em->getManager()->createQueryBuilder();
if($access=="admin"||$access=="user")
$qb->select('COUNT(user)')
->from('App:User','user')
->where($qb->expr()->exists($sub->getDQL()))
->setParameter("groupid",$id);
else {
$usermodo=$this->getUser()->getId();
$qb->select('COUNT(user)')
->from('App:User','user')
->from('App:UserModo','usermodo')
->where($qb->expr()->exists($sub->getDQL()))
->andWhere("usermodo.niveau01 = user.niveau01")
->andWhere("usermodo.user = :userid")
->setParameter("userid", $usermodo)
->setParameter("groupid",$id);
}
$total=$qb->getQuery()->getSingleScalarResult();
// Nombre d'enregistrement filtré
if($search["value"]=="")
$totalf = $total;
else {
if($access=="admin"||$access=="user")
$totalf= $em->getManager()->createQueryBuilder()
->select('COUNT(user)')
->from('App:User','user')
->where('user.username LIKE :value OR user.email LIKE :value')
->andWhere($qb->expr()->exists($sub->getDQL()))
->setParameter("value", "%".$search["value"]."%")
->setParameter("groupid",$id)
->getQuery()
->getSingleScalarResult();
else
$totalf= $em->getManager()->createQueryBuilder()
->select('COUNT(user)')
->from('App:User','user')
->from('App:UserModo','usermodo')
->where('user.username LIKE :value OR user.email LIKE :value')
->andWhere($qb->expr()->exists($sub->getDQL()))
->andWhere("usermodo.niveau01 = user.niveau01")
->andWhere("usermodo.user = :userid")
->setParameter("userid", $usermodo)
->setParameter("value", "%".$search["value"]."%")
->setParameter("groupid",$id)
->getQuery()
->getSingleScalarResult();
}
// Construction du tableau de retour
$output = array(
'draw' => $draw,
'recordsFiltered' => $totalf,
'recordsTotal' => $total,
'data' => array(),
);
// Parcours des Enregistrement
$qb = $em->getManager()->createQueryBuilder();
$qb->select('user')->from("App:User",'user');
if($access=="admin"||$access=="user")
$qb->where($qb->expr()->exists($sub->getDQL()));
else
$qb->from('App:UserModo','usermodo')
->where($qb->expr()->exists($sub->getDQL()))
->andWhere("usermodo.niveau01 = user.niveau01")
->andWhere("usermodo.user = :userid")
->setParameter("userid", $usermodo);
if($search["value"]!="") {
$qb ->andWhere('user.username LIKE :value OR user.email LIKE :value')
->setParameter("value", "%".$search["value"]."%");
}
$qb->setParameter("groupid",$id);
switch($ordercolumn) {
case 2 :
$qb->orderBy('user.username',$orderdir);
break;
case 3 :
$qb->orderBy('user.email',$orderdir);
break;
}
$datas=$qb->setFirstResult($start)->setMaxResults($length)->getQuery()->getResult();
foreach($datas as $data) {
// Propriétaire
$usergroup=$em->getRepository("App\Entity\UserGroup")->findOneBy(["user"=>$data->getId(),"group"=>$id]);
$fgproprio=($usergroup->getUser()==$group->getOwner());
$fgme=($usergroup->getUser()==$this->getUser()&&$access!="admin");
// Action
$action = "";
if($this->canupdatemember($access,$group,$em,false)&&!$fgproprio&&!$fgme)
$action.="<a style='cursor:pointer' onClick='delUsers(".$data->getId().")'><i class='fa fa-minus fa-fw'></i></a>";
// Avatar
if(stripos($data->getAvatar(),"http")===0)
$avatar="<img src='".$data->getAvatar()."' class='avatar'>";
else
$avatar="<img src='".$this->getParameter('appAlias')."uploads/avatar/".$data->getAvatar()."' class='avatar'>";
// Flag manager
$rolegroup="";
if($fgproprio) $rolegroup="Propriétaire du groupe";
elseif($this->canupdatemember($access,$group,$em,false)&&!$fgme) {
$selectuser=($usergroup->getRolegroup()==0?"selected='selected'":"");
$selectwritter=($usergroup->getRolegroup()==50?"selected='selected'":"");
$selectmanager=($usergroup->getRolegroup()==90?"selected='selected'":"");
$rolegroup='<select id="roleuser-'.$data->getId().'" name="user[visible]" onChange="changeRole('.$data->getId().');"><option value="0" '.$selectuser.'>Utilisateur</option><option value="50" '.$selectwritter.'>Collaborateur</option><option value="90" '.$selectmanager.'>Gestionnaire</option></select>';
}
else $rolegroup=($usergroup->getRolegroup()==0?"Utilisateur":($usergroup->getRolegroup()==50?"Collaborateur":"Gestionnaire"));
$tmp=array("DT_RowId"=>"user".$data->getId(),$action,$avatar,$data->getUsername(),$data->getEmail(),$rolegroup);
array_push($output["data"],$tmp);
}
// Retour
return new JsonResponse($output);
}
public function useradd($groupid,$userid,$access,Request $request,ManagerRegistry $em)
{
// Récupération de l'enregistrement courant
$group=$em->getRepository($this->entity)->find($groupid);
if (!$group) throw $this->createNotFoundException('Unable to find entity.');
$user=$em->getRepository("App\Entity\User")->find($userid);
if (!$user) throw $this->createNotFoundException('Unable to find entity.');
$output=array();
$this->canupdatemember($access,$group,$em,true);
$usergroup = $em->getRepository("App\Entity\UserGroup")->findOneBy(array("user"=>$user,"group"=>$group));
if($usergroup) return new JsonResponse($output);
$usergroup=new UserGroup();
$usergroup->setUser($user);
$usergroup->setGroup($group);
$usergroup->setApikey(Uuid::uuid4());
$usergroup->setRolegroup(0);
$em->getManager()->persist($usergroup);
$em->getManager()->flush();
// Retour
return new JsonResponse($output);
}
public function userdel($groupid,$userid,$access,Request $request,ManagerRegistry $em)
{
// Récupération de l'enregistrement courant
$group=$em->getRepository($this->entity)->find($groupid);
if (!$group) throw $this->createNotFoundException('Unable to find entity.');
$user=$em->getRepository("App\Entity\User")->find($userid);
if (!$user) throw $this->createNotFoundException('Unable to find entity.');
$output=array();
$this->canupdatemember($access,$group,$em,true);
if($user==$group->getOwner()) throw $this->createAccessDeniedException('Permission denied');
$usergroup = $em->getRepository("App\Entity\UserGroup")->findOneBy(array("user"=>$user,"group"=>$group));
if($usergroup) {
$em->getManager()->remove($usergroup);
$em->getManager()->flush();
}
// Retour
return new JsonResponse($output);
}
public function userchangerole($groupid,$userid,$roleid,$access,Request $request,ManagerRegistry $em)
{
// Récupération de l'enregistrement courant
$group=$em->getRepository($this->entity)->find($groupid);
if (!$group) throw $this->createNotFoundException('Unable to find entity.');
$user=$em->getRepository("App\Entity\User")->find($userid);
if (!$user) throw $this->createNotFoundException('Unable to find entity.');
$output=array();
$this->canupdatemember($access,$group,$em,true);
if($user==$group->getOwner()) throw $this->createAccessDeniedException('Permission denied');
$usergroup = $em->getRepository("App\Entity\UserGroup")->findOneBy(array("user"=>$user,"group"=>$group));
if($usergroup) {
$usergroup->setRolegroup($roleid);
$em->getManager()->persist($usergroup);
$em->getManager()->flush();
}
// Retour
return new JsonResponse($output);
}
public function userout($id,$access,Request $request,ManagerRegistry $em)
{
// Récupération de l'enregistrement courant
$group=$em->getRepository($this->entity)->find($id);
if (!$group) throw $this->createNotFoundException('Unable to find entity.');
// On ne peut se désinscrire que si le groupe est ouvert et qu'il n'est pas lié à un groupe ldap ou sso
if($group->getOwner()!=$this->getUser()&&($group->isIsOpen()||$this->canupdatemember($access,$group,$em,false))) {
$usergroup = $em->getRepository("App\Entity\UserGroup")->findOneBy(array("user"=>$this->getUser(),"group"=>$group));
if($usergroup) {
$em->getManager()->remove($usergroup);
$em->getManager()->flush();
}
}
return $this->redirectToRoute(str_replace("_admin_","_".$access."_",$this->route));
}
private function cansubmit($access,$em) {
switch($access) {
case "admin" : return true; break;
case "user" : return true; break;
}
throw $this->createAccessDeniedException('Permission denied');
}
private function canupdate($access,$entity,$em,$fgblock=true) {
$toreturn=false;
switch($access) {
case "admin" : $toreturn=($entity->getId()>0); break;
case "user":
if(!$entity->isIsworkgroup()||$entity->getOwner()!=$this->getUser()) $toreturn=false;
else $toreturn=true;
break;
}
if($fgblock&&!$toreturn) throw $this->createAccessDeniedException('Permission denied');
return $toreturn;
}
private function canseemember($access,$entity,$em,$fgblock=true) {
switch($access) {
case "admin" : $toreturn=($entity->getId()>0); break;
case "modo" : $toreturn=($entity->getId()>0); break;
case "user":
$usergroup=$em->getRepository("App\Entity\UserGroup")->findOneBy(["user"=>$this->getUser(),"group"=>$entity]);
if(!$usergroup||!$entity->isIsworkgroup()||$entity->getId()<0) $toreturn=false;
else $toreturn=true;
break;
}
if($fgblock&&!$toreturn) throw $this->createAccessDeniedException('Permission denied');
return $toreturn;
}
private function canupdatemember($access,$entity,$em,$fgblock=true) {
$toreturn=false;
switch($access) {
case "admin" : $toreturn=($entity->getId()>0&&!$entity->getLdapfilter()); break;
case "modo" : $toreturn=($entity->getId()>0); break;
case "user":
$usergroup=$em->getRepository("App\Entity\UserGroup")->findOneBy(["user"=>$this->getUser(),"group"=>$entity]);
if(!$usergroup||!$entity->isIsworkgroup()||$entity->getId()<0) $toreturn=false;
elseif($usergroup->getRolegroup()<90) $toreturn=false;
else $toreturn=true;
break;
}
if($fgblock&&!$toreturn) throw $this->createAccessDeniedException('Permission denied');
return $toreturn;
}
}

View File

@ -0,0 +1,81 @@
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Filesystem\Filesystem;
class HomeController extends AbstractController
{
public function home(Request $request): Response
{
if($request->getSession()->get("fgforceconnect"))
return $this->redirectToRoute("app_user_home");
return $this->render('Home/home.html.twig',[
"useheader"=>true,
"usemenu"=>true,
"usesidebar"=>false,
"maxsize"=>1000,
]);
}
public function homeuser($access): Response
{
return $this->render('Home/home.html.twig',[
"useheader"=>true,
"usemenu"=>false,
"usesidebar"=>false,
"maxsize"=>1000,
]);
}
public function homeadmin($access): Response
{
return $this->redirectToRoute("app_admin_config");
}
public function homemodo($access): Response
{
return $this->redirectToRoute("app_modo_niveau02");
}
public function docrest(): Response
{
return $this->render('Home/docrest.html.twig',[
"useheader"=>true,
"usemenu"=>false,
"usesidebar"=>true,
]);
}
public function upload($access,Request $request): Response
{
// Fichier temporaire uploadé
$tmpfile = $request->files->get('upload');
$extention = $tmpfile->getClientOriginalExtension();
// Répertoire de Destination
$fs = new Filesystem();
$rootdir = $this->getParameter('kernel.project_dir') . '/public';
$fs->mkdir($rootdir."/uploads/ckeditor");
// Fichier cible
$targetName = uniqid().".".$extention;
$targetFile = $rootdir."/uploads/ckeditor/".$targetName;
$targetUrl = $this->getParameter('appAlias')."uploads/ckeditor/".$targetName;
$message = "";
move_uploaded_file($tmpfile,$targetFile);
$output["uploaded"]=1;
$output["fileName"]=$targetName;
$output["url"]=$targetUrl;
return new Response(json_encode($output));
}
}

View File

@ -0,0 +1,198 @@
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Doctrine\Persistence\ManagerRegistry;
use Ramsey\Uuid\Uuid;
use App\Entity\Niveau01 as Entity;
use App\Form\Niveau01Type as Form;
class Niveau01Controller extends AbstractController
{
private $data="niveau01";
private $entity="App\Entity\Niveau01";
private $twig="Niveau01/";
private $route="app_admin_niveau01";
public function list(): Response
{
return $this->render($this->twig.'list.html.twig',[
"useheader"=>true,
"usemenu"=>false,
"usesidebar"=>true,
]);
}
public function tablelist(Request $request,ManagerRegistry $em): Response
{
$query=$request->query->all();
$start=$query['start'];
$length=$query['length'];
$search=$query['search'];
$draw= $query['draw'];
$ordercolumn=$query['order'][0]['column'];
$orderdir=$query['order'][0]['dir'];
// Nombre total d'enregistrement
$total = $em->getManager()->createQueryBuilder()->select('COUNT(entity)')->from($this->entity,'entity')->getQuery()->getSingleScalarResult();
// Nombre d'enregistrement filtré
if(!$search||$search["value"]=="")
$totalf = $total;
else {
$totalf= $em->getManager()->createQueryBuilder()
->select('COUNT(entity)')
->from($this->entity,'entity')
->where('entity.label LIKE :value')
->setParameter("value", "%".$search["value"]."%")
->getQuery()
->getSingleScalarResult();
}
// Construction du tableau de retour
$output = array(
'draw' => $draw,
'recordsFiltered' => $totalf,
'recordsTotal' => $total,
'data' => array(),
);
// Parcours des Enregistrement
$qb = $em->getManager()->createQueryBuilder();
$qb->select('entity')->from($this->entity,'entity');
if($search&&$search["value"]!="") {
$qb ->andWhere('entity.label LIKE :value')
->setParameter("value", "%".$search["value"]."%");
}
if($ordercolumn) {
switch($ordercolumn) {
case 1 :
$qb->orderBy('entity.label',$orderdir);
break;
}
}
$datas=$qb->setFirstResult($start)->setMaxResults($length)->getQuery()->getResult();
foreach($datas as $data) {
// Action
$action = "";
$action.="<a href='".$this->generateUrl($this->route.'_update', array('id'=>$data->getId()))."'><i class='fa fa-file fa-fw fa-2x'></i></a>";
$tmp=array();
array_push($tmp,$action);
array_push($tmp,$data->getLabel());
if($this->getParameter("appMasteridentity")=="LDAP"||$this->getParameter("appSynchro")=="LDAP2NINE") array_push($tmp,$data->getLdapfilter());
if($this->getParameter("appMasteridentity")=="SSO") array_push($tmp,$data->getAttributes());
array_push($output["data"],$tmp);
}
// Retour
return new JsonResponse($output);
}
public function submit(Request $request,ManagerRegistry $em): Response
{
// Initialisation de l'enregistrement
$data = new Entity();
$data->setApikey(Uuid::uuid4());
// Création du formulaire
$form = $this->createForm(Form::class,$data,array(
"mode"=>"submit",
"appMasteridentity"=>$this->GetParameter("appMasteridentity"),
"appSynchro"=>$this->GetParameter("appSynchro"),
"appNiveau01label"=>$this->GetParameter("appNiveau01label"),
));
// Récupération des data du formulaire
$form->handleRequest($request);
// Sur validation
if ($form->get('submit')->isClicked() && $form->isValid()) {
$data = $form->getData();
// Sauvegarde
$em->getManager()->persist($data);
$em->getManager()->flush();
// Retour à la liste
return $this->redirectToRoute($this->route);
}
// Affichage du formulaire
return $this->render($this->twig.'edit.html.twig', [
"useheader"=>true,
"usemenu"=>false,
"usesidebar"=>true,
"mode"=>"submit",
"form"=>$form->createView(),
$this->data=>$data,
]);
}
public function update($id,Request $request,ManagerRegistry $em): Response
{
// Initialisation de l'enregistrement
$data=$em->getRepository($this->entity)->find($id);
if (!$data) throw $this->createNotFoundException('Unable to find entity.');
// Création du formulaire
$form = $this->createForm(Form::class,$data,array(
"mode"=>"update",
"appMasteridentity"=>$this->GetParameter("appMasteridentity"),
"appSynchro"=>$this->GetParameter("appSynchro"),
"appNiveau01label"=>$this->GetParameter("appNiveau01label"),
));
// Récupération des data du formulaire
$form->handleRequest($request);
// Sur validation
if ($form->get('submit')->isClicked() && $form->isValid()) {
$data = $form->getData();
$em->getManager()->flush();
// Retour à la liste
return $this->redirectToRoute($this->route);
}
// Affichage du formulaire
return $this->render($this->twig.'edit.html.twig', [
'useheader' => true,
'usemenu' => false,
'usesidebar' => true,
$this->data => $data,
'mode' => 'update',
'form' => $form->createView()
]);
}
public function delete($id,Request $request,ManagerRegistry $em): Response
{
// Récupération de l'enregistrement courant
$data=$em->getRepository($this->entity)->find($id);
if (!$data) throw $this->createNotFoundException('Unable to find entity.');
// Tentative de suppression
try{
$em->getManager()->remove($data);
$em->getManager()->flush();
}
catch (\Exception $e) {
$request->getSession()->getFlashBag()->add("error", $e->getMessage());
return $this->redirectToRoute($this->route."_update",["id"=>$id]);
}
return $this->redirectToRoute($this->route);
}
}

View File

@ -0,0 +1,326 @@
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Doctrine\Persistence\ManagerRegistry;
use Ramsey\Uuid\Uuid;
use App\Entity\Niveau02 as Entity;
use App\Form\Niveau02Type as Form;
class Niveau02Controller extends AbstractController
{
private $data="niveau02";
private $entity="App\Entity\Niveau02";
private $twig="Niveau02/";
private $route="app_admin_niveau02";
public function list($access): Response
{
return $this->render($this->twig.'list.html.twig',[
"useheader"=>true,
"usemenu"=>false,
"usesidebar"=>true,
"access"=>$access,
]);
}
public function tablelist($access,Request $request,ManagerRegistry $em): Response
{
$query=$request->query->all();
$start=$query['start'];
$length=$query['length'];
$search=$query['search'];
$draw= $query['draw'];
$ordercolumn=$query['order'][0]['column'];
$orderdir=$query['order'][0]['dir'];
// Nombre total d'enregistrement
switch($access) {
case "admin":
$total = $em->getManager()->createQueryBuilder()->select('COUNT(entity)')->from($this->entity,'entity')->getQuery()->getSingleScalarResult();
break;
case "modo":
$total = $em->getManager()->createQueryBuilder()
->select('COUNT(entity)')
->from($this->entity,'entity')
->from("App\Entity\UserModo",'usermodo')
->where("usermodo.niveau01 = entity.niveau01")
->andWhere("usermodo.user = :user")
->setParameter("user", $this->getUser())
->getQuery()->getSingleScalarResult();
break;
}
// Nombre d'enregistrement filtré
if(!$search||$search["value"]=="")
$totalf = $total;
else {
switch($access) {
case "admin":
$totalf= $em->getManager()->createQueryBuilder()
->select('COUNT(entity)')
->from($this->entity,'entity')
->from("App\Entity\Niveau01",'niveau01')
->where('entity.niveau01=niveau01.id')
->andwhere('entity.label LIKE :value OR niveau01.label LIKE :value')
->setParameter("value", "%".$search["value"]."%")
->getQuery()
->getSingleScalarResult();
break;
case "modo":
$totalf= $em->getManager()->createQueryBuilder()
->select('COUNT(entity)')
->from($this->entity,'entity')
->from("App\Entity\Niveau01",'niveau01')
->from("App\Entity\UserModo",'usermodo')
->where('entity.niveau01=niveau01.id')
->andwhere('entity.label LIKE :value OR niveau01.label LIKE :value')
->andWhere("usermodo.niveau01 = entity.niveau01")
->andWhere("usermodo.user = :user")
->setParameter("value", "%".$search["value"]."%")
->setParameter("user", $this->getUser())
->getQuery()
->getSingleScalarResult();
break;
}
}
// Construction du tableau de retour
$output = array(
'draw' => $draw,
'recordsFiltered' => $totalf,
'recordsTotal' => $total,
'data' => array(),
);
// Parcours des Enregistrement
$qb = $em->getManager()->createQueryBuilder();
switch($access) {
case "admin":
$qb->select('entity')
->from($this->entity,'entity')
->from("App:Niveau01",'niveau01')
->where('entity.niveau01=niveau01.id');
break;
case "modo":
$qb->select('entity')
->from($this->entity,'entity')
->from("App:Niveau01",'niveau01')
->from("App\Entity\UserModo",'usermodo')
->where('entity.niveau01=niveau01.id')
->andWhere("usermodo.niveau01 = entity.niveau01")
->andWhere("usermodo.user = :user")
->setParameter("user", $this->getUser());
break;
}
if($search&&$search["value"]!="") {
$qb ->andwhere('entity.label LIKE :value OR niveau01.label LIKE :value')
->setParameter("value", "%".$search["value"]."%");
}
if($ordercolumn) {
switch($ordercolumn) {
case 1 :
$qb->orderBy('niveau01.label',$orderdir);
break;
case 2 :
$qb->orderBy('entity.label',$orderdir);
break;
}
}
$datas=$qb->setFirstResult($start)->setMaxResults($length)->getQuery()->getResult();
foreach($datas as $data) {
// Action
$action = "";
switch($access) {
case "admin":
$action.="<a href='".$this->generateUrl($this->route.'_update', array('id'=>$data->getId()))."'><i class='fa fa-file fa-fw fa-2x'></i></a>";
break;
case "modo":
$action.="<a href='".$this->generateUrl(str_replace("_admin_","_modo_",$this->route).'_update', array('id'=>$data->getId()))."'><i class='fa fa-file fa-fw fa-2x'></i></a>";
break;
}
$tmp=array();
array_push($tmp,$action);
array_push($tmp,$data->getNiveau01()->getLabel());
array_push($tmp,$data->getLabel());
array_push($output["data"],$tmp);
}
// Retour
return new JsonResponse($output);
}
public function selectlist(Request $request,ManagerRegistry $em): Response
{
$output=array();
$page_limit=$request->query->get('page_limit');
$q=$request->query->get('q');
$niveau01id=$request->get('niveau01');
$qb = $em->getManager()->createQueryBuilder();
$qb->select('entity')
->from($this->entity,'entity')
->where('entity.label LIKE :value')
->andwhere('entity.niveau01=:niveau01')
->setParameter("value", "%".$q."%")
->setParameter("niveau01", $niveau01id)
->orderBy('entity.label');
$datas=$qb->setFirstResult(0)->setMaxResults($page_limit)->getQuery()->getResult();
foreach($datas as $data) {
array_push($output,array("id"=>$data->getId(),"text"=>$data->getLabel()));
}
$ret_string["results"]=$output;
$response = new Response(json_encode($ret_string));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
public function submit($access,Request $request,ManagerRegistry $em): Response
{
// Initialisation de l'enregistrement
$data = new Entity();
$data->setApikey(Uuid::uuid4());
// Controler les permissions
$this->cansubmit($access,$em);
// Création du formulaire
$form = $this->createForm(Form::class,$data,array(
"mode"=>"submit",
"access"=>$access,
"userid"=>$this->getUser()->getId(),
"appMasteridentity"=>$this->GetParameter("appMasteridentity"),
"appNiveau01label"=>$this->GetParameter("appNiveau01label"),
"appNiveau02label"=>$this->GetParameter("appNiveau02label"),
));
// Récupération des data du formulaire
$form->handleRequest($request);
// Sur validation
if ($form->get('submit')->isClicked() && $form->isValid()) {
$data = $form->getData();
// Sauvegarde
$em->getManager()->persist($data);
$em->getManager()->flush();
// Retour à la liste
return $this->redirectToRoute(str_replace("_admin_","_".$access."_",$this->route));
}
// Affichage du formulaire
return $this->render($this->twig.'edit.html.twig', [
"useheader"=>true,
"usemenu"=>false,
"usesidebar"=>true,
"mode"=>"submit",
"access"=>$access,
"form"=>$form->createView(),
$this->data=>$data,
]);
}
public function update($id,$access,Request $request,ManagerRegistry $em): Response
{
// Initialisation de l'enregistrement
$data=$em->getRepository($this->entity)->find($id);
if (!$data) throw $this->createNotFoundException('Unable to find entity.');
// Controler les permissions
$this->canupdate($access,$data,$em);
// Création du formulaire
$form = $this->createForm(Form::class,$data,array(
"mode"=>"update",
"appMasteridentity"=>$this->GetParameter("appMasteridentity"),
"appNiveau01label"=>$this->GetParameter("appNiveau01label"),
"appNiveau02label"=>$this->GetParameter("appNiveau02label"),
));
// Récupération des data du formulaire
$form->handleRequest($request);
// Sur validation
if ($form->get('submit')->isClicked() && $form->isValid()) {
$data = $form->getData();
$em->getManager()->flush();
// Retour à la liste
return $this->redirectToRoute(str_replace("_admin_","_".$access."_",$this->route));
}
// Affichage du formulaire
return $this->render($this->twig.'edit.html.twig', [
'useheader' => true,
'usemenu' => false,
'usesidebar' => true,
$this->data => $data,
'mode' => 'update',
'access' => $access,
'form' => $form->createView()
]);
}
public function delete($id,$access,Request $request,ManagerRegistry $em): Response
{
// Récupération de l'enregistrement courant
$data=$em->getRepository($this->entity)->find($id);
if (!$data) throw $this->createNotFoundException('Unable to find entity.');
// Controler les permissions
$this->canupdate($access,$data,$em);
// Tentative de suppression
try{
$em->getManager()->remove($data);
$em->getManager()->flush();
}
catch (\Exception $e) {
$request->getSession()->getFlashBag()->add("error", $e->getMessage());
return $this->redirectToRoute(str_replace("_admin_","_".$access."_",$this->route)."_update",["id"=>$id]);
}
return $this->redirectToRoute(str_replace("_admin_","_".$access."_",$this->route));
}
private function cansubmit($access,$em) {
switch($access) {
case "admin" : return true; break;
case "modo" : return true; break;
}
throw $this->createAccessDeniedException('Permission denied');
}
private function canupdate($access,$entity,$em) {
switch($access) {
case "admin" : return true; break;
case "modo" :
$usermodo=$em->getRepository("App\Entity\UserModo")->findOneBy(["user"=>$this->getUser(),"niveau01"=>$entity->getNiveau01()]);
if(!$usermodo) throw $this->createAccessDeniedException('Permission denied');
return true;
break;
}
throw $this->createAccessDeniedException('Permission denied');
}
}

View File

@ -0,0 +1,27 @@
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Mercure\HubInterface;
use Symfony\Component\Mercure\Update;
class PublishController extends AbstractController
{
public function publish($channel, $id, Request $request, HubInterface $hub): Response
{
$ret=$request->get("msg");
$ret["from"]=[];
$ret["from"]["id"]="tot";
$update = new Update(
$channel."-".$id,
json_encode(
['ret' => $ret])
);
$hub->publish($update);
return new Response('published!');
}
}

View File

@ -0,0 +1,737 @@
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Component\Form\FormError;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use App\Service\MailService;
use Ramsey\Uuid\Uuid;
use App\Entity\User;
use App\Entity\Usergroup;
use App\Entity\Registration;
use App\Form\RegistrationType as Form;
use App\Form\ResetpwdType;
class RegistrationController extends AbstractController
{
private $data="registration";
private $entity="App\Entity\Registration";
private $twig="Registration/";
private $route="app_admin_registration";
private $mail;
public function __construct(MailService $mail) {
$this->mail = $mail;
}
public function list($access)
{
$appmoderegistration = $this->getParameter('appModeregistration');
$appMasteridentity = $this->getParameter('appMasteridentity');
if($appmoderegistration=="none"||$appMasteridentity!="SQL")
throw $this->createAccessDeniedException('Permission denied');
return $this->render($this->twig.'list.html.twig',[
'useheader' => true,
'usemenu' => false,
'usesidebar' => true,
'access' => $access,
]);
}
public function tablelist($access, Request $request,ManagerRegistry $em): Response
{
$query=$request->query->all();
$start=$query['start'];
$length=$query['length'];
$search=$query['search'];
$draw= $query['draw'];
$ordercolumn=$query['order'][0]['column'];
$orderdir=$query['order'][0]['dir'];
// Nombre total d'enregistrement
if($access=="admin")
$total = $em->getManager()->createQueryBuilder()->select('COUNT(entity)')->from($this->entity,'entity')->getQuery()->getSingleScalarResult();
else {
$usermodo=$this->getUser();
$total = $em->getManager()->createQueryBuilder()
->select('COUNT(entity)')
->from($this->entity,'entity')
->from("App:UserModo",'usermodo')
->where("usermodo.niveau01 = entity.niveau01")
->andWhere("usermodo.user = :user")
->setParameter("user", $usermodo)
->getQuery()->getSingleScalarResult();
}
// Nombre d'enregistrement filtré
if($search["value"]=="")
$totalf = $total;
else {
if($access=="admin")
$totalf= $em->getManager()->createQueryBuilder()
->select('COUNT(entity)')
->from($this->entity,'entity')
->where('entity.username LIKE :value')
->orWhere('entity.email LIKE :value')
->setParameter("value", "%".$search["value"]."%")
->getQuery()
->getSingleScalarResult();
else
$totalf= $em->getManager()->createQueryBuilder()
->select('COUNT(entity)')
->from($this->entity,'entity')
->from("App:UserModo",'usermodo')
->where('entity.username LIKE :value OR entity.email LIKE :value')
->andWhere("usermodo.niveau01 = entity.niveau01")
->andWhere("usermodo.user = :user")
->setParameter("value", "%".$search["value"]."%")
->setParameter("user", $usermodo)
->getQuery()
->getSingleScalarResult();
}
// Construction du tableau de retour
$output = array(
'draw' => $draw,
'recordsFiltered' => $totalf,
'recordsTotal' => $total,
'data' => array(),
);
// Parcours des Enregistrement
$qb = $em->getManager()->createQueryBuilder();
if($this->isGranted('ROLE_ADMIN')) {
$qb->select('entity')->from($this->entity,'entity')->from('App:Niveau01','niveau01');
$qb->where('entity.niveau01=niveau01.id');
}
else{
$qb->select('entity')->from($this->entity,'entity')->from('App:Niveau01','niveau01')->from("App:UserModo",'usermodo');
$qb->where('entity.niveau01=niveau01.id')
->andWhere("usermodo.niveau01 = entity.niveau01")
->andWhere("usermodo.user = :user")
->setParameter("user", $usermodo);
}
if($search["value"]!="") {
$qb ->andWhere('entity.username LIKE :value OR entity.email LIKE :value OR niveau01.label LIKE :value')
->setParameter("value", "%".$search["value"]."%");
}
switch($ordercolumn) {
case 1 :
$qb->orderBy('entity.username',$orderdir);
break;
case 2 :
$qb->orderBy('entity.email',$orderdir);
break;
case 3 :
$qb->orderBy('entity.label',$orderdir);
break;
case 4 :
$qb->orderBy('entity.statut',$orderdir);
break;
case 5 :
$qb->orderBy('entity.keyexpire',$orderdir);
break;
}
$datas=$qb->setFirstResult($start)->setMaxResults($length)->getQuery()->getResult();
foreach($datas as $data) {
$action ="";
// Si inscription non périmée
if($data->getStatut()<=2) {
$action.="<a href='".$this->generateUrl('app_'.$access.'_registration_update', array('id'=>$data->getId()))."'><i class='fa fa-envelope fa-2x fa-fw'></i></a>";
}
$statut="";
switch($data->getStatut()) {
case 1: $statut='En attente validation Administration'; break;
case 2: $statut='En attente validation Utilisateur'; break;
case 3: $statut='Inscription expirée'; break;
}
array_push($output["data"],array(
$action,
$data->getUsername(),
$data->getEmail(),
$data->getNiveau01()->getLabel(),
$statut,
(is_null($data->getKeyexpire())?"":$data->getKeyexpire()->format('d/m/Y H:i:s'))
));
}
// Retour
return new JsonResponse($output);
}
public function submit(Request $request,ManagerRegistry $em): Response
{
$appmoderegistration = $this->getParameter('appModeregistration');
$appMasteridentity = $this->getParameter('appMasteridentity');
if($appmoderegistration=="none"||$appMasteridentity!="SQL")
throw $this->createAccessDeniedException('Permission denied');
$data = new Registration();
$data->setIsvisible(true);
// Création du formulaire
$form = $this->createForm(Form::class,$data,array(
"mode"=>"submit",
"access"=>"user",
"userid"=>null,
"appMasteridentity"=>$this->GetParameter("appMasteridentity"),
"appNiveau01label"=>$this->GetParameter("appNiveau01label"),
"appNiveau02label"=>$this->GetParameter("appNiveau02label"),
));
// Récupération des data du formulaire
$form->handleRequest($request);
// si mode de registration byuser
if($appmoderegistration=="byuser") {
$idstatut=2;
}
else {
// On recherche le domaine du mail dans la liste blanche
$email=explode("@",$data->getEmail());
$domaine=end($email);
$whitelist = $em->getRepository("App\Entity\Whitelist")->findBy(["label"=>$domaine]);
$idstatut=(!$whitelist?1:2);
}
$data->setStatut($idstatut);
// Sur erreur
$this->getErrorForm(null,$form,$request,$data,"submit",$idstatut);
// Sur validation
if ($form->get('submit')->isClicked() && $form->isValid()) {
$data = $form->getData();
$appname = $request->getSession()->get('appname');
$noreply = $this->getParameter('appMailnoreply');
$appModeregistrationterme = $this->getParameter('appModeregistrationterme');
// si non : validation par administrateur
if($idstatut==1) {
// Email à destination de l'inscript pour le prévenir qu'un administrateur doit valider
$subject=$appname." : Inscription en cours de validation";
$body="Votre inscription a bien été enregistrée.<br>Cependant, un administrateur doit encore valider votre inscription avant que celle-ci ne devienne effective.<br><br>Vous recevrez un mail quand votre inscription sera validée";
$info=$body;
$to = $data->getEmail();
$from = $noreply;
$fromName = $appname;
$this->mail->sendEmail($subject, $body, $to, $from, $fromName);
// Email à l'ensemble administrateurs pour les prévenir qu'il y a une personne à valider
$url = $this->generateUrl('app_admin_registration', [], UrlGeneratorInterface::ABSOLUTE_URL);
$to=array();
$from = $noreply;
$fromName = $appname;
$subject=$appname." : Inscription à valider";
$motivation = "Login = ".$data->getUsername()."<br>";
$motivation.= "Nom = ".$data->getLastname()."<br>";
$motivation.= "Prénom = ".$data->getFirstname()."<br>";
$motivation.= "Mail = ".$data->getEmail()."<br>";
$motivation.= $this->getParameter("appNiveau01label")." = ".$data->getNiveau01()->getLabel();
$motivation.= $data->getMotivation();
$body="Un utilisateur dont le mail nest pas en liste blanche souhaite sinscrire à ".$appname.".\nMerci dapprouver son inscription pour finaliser celle-ci.<br><br>Veuillez vérifier cette inscription à cette adresse:<br><a href='$url'>$url</a><br><br>".$motivation;
$emailadmins= $em ->getManager()->createQueryBuilder()
->select('table.email')
->from("App:User",'table')
->where('table.roles LIKE :value')
->setParameter("value", "%ROLE_ADMIN%")
->getQuery()
->getResult(\Doctrine\ORM\Query::HYDRATE_SCALAR);
foreach($emailadmins as $emailadmin) {
array_push($to,$emailadmin["email"]);
}
$this->mail->sendEmail($subject, $body, $to, $from, $fromName);
// Email à l'ensemble des modérateurs du service pour les prévenir qu'il y a une personne à valider
$niveau01id=$data->getNiveau01()->getId();
$url = $this->generateUrl('app_modo_registration', [], UrlGeneratorInterface::ABSOLUTE_URL);
$to=array();
$from = $noreply;
$fromName = $appname;
$subject=$appname." : Inscription à valider";
$motivation = "Login = ".$data->getUsername()."<br>";
$motivation.= "Nom = ".$data->getLastname()."<br>";
$motivation.= "Prénom = ".$data->getFirstname()."<br>";
$motivation.= "Mail = ".$data->getEmail()."<br>";
$motivation.= $this->getParameter("appNiveau01label")." = ".$data->getNiveau01()->getLabel();
$motivation.= $data->getMotivation();
$body="Un utilisateur dont le mail nest pas en liste blanche souhaite sinscrire à ".$appname.".\nMerci dapprouver son inscription pour finaliser celle-ci.<br><br>Veuillez vérifier cette inscription à cette adresse:<br><a href='$url'>$url</a><br><br>".$motivation;
$emailmodos= $em ->getManager()->createQueryBuilder()
->select('user.email')
->from("App:UserModo",'usermodo')
->from("App:User",'user')
->where("usermodo.niveau01 = :niveau01id")
->andWhere("user.id = usermodo.user")
->andWhere('user.roles LIKE :value')
->setParameter("niveau01id", $niveau01id)
->setParameter("value", "%ROLE_MODO%")
->getQuery()
->getResult(\Doctrine\ORM\Query::HYDRATE_SCALAR);
foreach($emailmodos as $emailmodo) {
array_push($to,$emailmodo["email"]);
}
$this->mail->sendEmail($subject, $body, $to, $from, $fromName);
}
// si oui : Domaine de confiance : email de validation d'inscription directement à l'utilisateur
else {
// Génération de la date de fin de validité de la clé
$keyexpire=new \DateTime();
$keyexpire->add(new \DateInterval('PT'.$appModeregistrationterme.'H'));
// Enregistrement des valeurs
$data->setKeyvalue(Uuid::uuid4());
$data->setKeyexpire($keyexpire);
// Email à l'utilisateur
$url = $this->generateUrl('app_registration_validation', array("key"=>$data->getKeyvalue()), UrlGeneratorInterface::ABSOLUTE_URL);
$subject=$appname." : confirmation de validation";
$body="<p>Merci de confirmer votre inscription en cliquant sur le lien suivant</p><p><a href='".$url."'>".$url."</a></p><br><p>Attention vous disposez dun délai de 8 heures pour le faire. Passé ce délai, vous devrez vous réinscrire.</p>";
$info="Vous allez recevoir un mail de confirmation pour finaliser votre inscription";
$to = $data->getEmail();
$from = $noreply;
$fromName = $appname;
$this->mail->sendEmail($subject, $body, $to, $from, $fromName);
}
// Sauvegarde
$em->getManager()->persist($data);
$em->getManager()->flush();
// A voir retour sur un écran d'info indiquant si validation par admion ou s'il doit matter ses email
$request->getSession()->set('registrationinfo', $info);
$request->getSession()->set('registrationmode', "info");
$request->getSession()->set('registrationredirectto', null);
return $this->redirectToRoute('app_registration_info');
}
else {
return $this->render($this->twig.'edit.html.twig', [
'useheader' => true,
'usemenu' => false,
'usesidebar' => false,
'maxsize' => 1200,
$this->data => $data,
'mode' => 'submit',
'form' => $form->createView()
]);
}
}
public function info(Request $request)
{
$info = $request->getSession()->get('registrationinfo');
$mode = $request->getSession()->get('registrationmode');
$redirectto = $request->getSession()->get('registrationredirectto');
return $this->render($this->twig.'info.html.twig', [
'useheader' => true,
'usemenu' => false,
'usesidebar' => false,
'maxwidth' => true,
'info' => $info,
'mode' => $mode,
'redirectto' => $redirectto,
]);
}
public function update($id,$access,Request $request,ManagerRegistry $em): Response
{
$appname = $request->getSession()->get('appname');
$noreply = $this->getParameter('appMailnoreply');
$appModeregistrationterme = $this->getParameter('appModeregistrationterme');
$appMasteridentity = $this->getParameter('appMasteridentity');
if($appModeregistrationterme=="none"||$appMasteridentity!="SQL")
throw $this->createAccessDeniedException('Permission denied');
// Initialisation de l'enregistrement
$data=$em->getRepository($this->entity)->find($id);
if (!$data) throw $this->createNotFoundException('Unable to find entity.');
// Controler les permissions
$this->canupdate($access,$data,$em);
// Création du formulaire
$form = $this->createForm(Form::class,$data,array(
"mode"=>"update",
"access"=>$access,
"userid"=>$this->getUser()->getId(),
"appMasteridentity"=>$this->GetParameter("appMasteridentity"),
"appNiveau01label"=>$this->GetParameter("appNiveau01label"),
"appNiveau02label"=>$this->GetParameter("appNiveau02label"),
));
// Récupération des data du formulaire
$form->handleRequest($request);
// Sur validation
if ($form->get('save')->isClicked() && $form->isValid()) {
$data = $form->getData();
// Sauvegarde
$em->getManager()->flush();
// Retour à la liste
return $this->redirectToRoute(str_replace("_admin_","_".$access."_",$this->route));
}
// Sur validation
if ($form->get('submit')->isClicked() && $form->isValid()) {
$data = $form->getData();
$appname = $request->getSession()->get('appname');
$noreply = $this->getParameter('appMailnoreply');
$appModeregistrationterme = $this->getParameter('appModeregistrationterme');
// Génération de la date de fin de validité de la clé
$keyexpire=new \DateTime();
$keyexpire->add(new \DateInterval('PT'.$appModeregistrationterme.'H'));
// Enregistrement des valeurs
$data->setKeyvalue(Uuid::uuid4());
$data->setKeyexpire($keyexpire);
// Statut en attente validation utilisateur
$data->setStatut(2);
// Email à l'utilisateur
$url = $this->generateUrl('app_registration_validation', array("key"=>$data->getKeyvalue()), UrlGeneratorInterface::ABSOLUTE_URL);
$subject=$appname." : confirmation de validation";
$body="<p>Merci de confirmer votre inscription en cliquant sur le lien suivant</p><p><a href='".$url."'>".$url."</a></p><br><p>Attention vous disposez dun délai de 8 heures pour le faire. Passé ce délai, vous devrez vous réinscrire.</p>";
$to = $data->getEmail();
$from = $noreply;
$fromName = $appname;
$this->mail->sendEmail($subject, $body, $to, $from, $fromName);
// Sauvegarde
$em->getManager()->flush();
// Retour à la liste
return $this->redirectToRoute(str_replace("_admin_","_".$access."_",$this->route));
}
// Affichage du formulaire
return $this->render($this->twig.'edit.html.twig', [
'useheader' => true,
'usemenu' => false,
'usesidebar' => true,
$this->data => $data,
'mode' => 'update',
'access' => $access,
'form' => $form->createView()
]);
}
public function validation($key,Request $request,ManagerRegistry $em)
{
$appmoderegistration = $this->getParameter('appModeregistration');
$appMasteridentity = $this->getParameter('appMasteridentity');
if($appmoderegistration=="none"||$appMasteridentity!="SQL")
throw $this->createAccessDeniedException('Permission denied');
$now=new \DateTime();
$data = $em ->getManager()->createQueryBuilder()
->select('entity')
->from($this->entity,'entity')
->where('entity.keyvalue= :key')
->andWhere('entity.keyexpire >= :date')
->setParameter("key", $key)
->setParameter("date", $now)
->getQuery()
->getSingleResult();
if(!$data) {
$info="Clé de validation invalide";
$mode="danger";
$request->getSession()->set('registrationinfo', $info);
$request->getSession()->set('registrationmode', $mode);
$request->getSession()->set('registrationredirectto', null);
}
else {
$url=$this->generateUrl('app_login');
$info="<p>Votre compte est à présent activé</p><p>Vous allez être redirigé vers la mire de connexion</p><p><a href='".$url."'>Connexion</a>";
$mode="success";
$request->getSession()->set('registrationinfo', $info);
$request->getSession()->set('registrationmode', $mode);
// Initialisation de l'enregistrement
$user = new User();
$user->setAvatar("noavatar.png");
$user->setUsername($data->getUsername());
$user->setEmail($data->getEmail());
$user->setLastname($data->getLastname());
$user->setFirstname($data->getFirstname());
$user->setSalt($data->getSalt());
$user->setPasswordDirect($data->getPassword());
$user->setIsvisible($data->isIsvisible());
$user->setMotivation($data->getMotivation());
$user->setNote($data->getNote());
$user->setApikey(Uuid::uuid4());
$user->setNiveau01($data->getNiveau01());
$user->setNiveau02($data->getNiveau02());
$user->setTelephonenumber($data->getTelephonenumber());
$user->setPostaladress($data->getPostaladress());
$user->setJob($data->getJob());
$user->setPosition($data->getPosition());
$user->setRoles(["ROLE_USER"]);
// Sauvegarde
$em->getManager()->persist($user);
$em->getManager()->flush();
// Suppression inscription
$em->getManager()->remove($data);
$em->getManager()->flush();
}
return $this->redirectToRoute('app_registration_info');
}
public function delete($id,$access,Request $request,ManagerRegistry $em)
{
// Récupération de l'enregistrement courant
$data=$em->getRepository($this->entity)->find($id);
if (!$data) throw $this->createNotFoundException('Unable to find entity.');
// Controler les permissions
$this->candelete($access,$data,$em);
// Tentative de suppression
try{
$em->getManager()->remove($data);
$em->getManager()->flush();
}
catch (\Exception $e) {
$request->getSession()->getFlashBag()->add("error", $e->getMessage());
return $this->redirectToRoute(str_replace("_admin_","_".$access."_",$this->route)."_update",["id"=>$id]);
}
return $this->redirectToRoute(str_replace("_admin_","_".$access."_",$this->route));
}
public function resetpwd01(Request $request,ManagerRegistry $em)
{
$appmoderegistration = $this->getParameter('appModeregistration');
$appMasteridentity = $this->getParameter('appMasteridentity');
if($appMasteridentity!="SQL")
throw $this->createAccessDeniedException('Permission denied');
// Création du formulaire
$form = $this->createForm(ResetpwdType::class,null,array("mode"=>"resetpwd01"));
// Récupération des data du formulaire
$form->handleRequest($request);
$data = $form->getData();
if ($form->get('submit')->isClicked()) {
$user=$em->getRepository("App\Entity\User")->findOneby(["email"=>$data->getEmail()]);
// On s'assure que le mail existe dans la base des utilisateurs
if(!$user) {
$request->getSession()->getFlashBag()->add("error", 'Mail inconnu');
// Affichage du formulaire
dump("here");
return $this->render($this->twig.'resetpwd01.html.twig', [
'useheader' => true,
'usemenu' => false,
'usesidebar' => false,
'maxsize' => 1200,
'form' => $form->createView()
]);
}
}
// Sur validation
if ($form->get('submit')->isClicked()) {
$user=$em->getRepository("App\Entity\User")->findOneby(["email"=>$data->getEmail()]);
$appname = $request->getSession()->get('appname');
$noreply = $this->getParameter('appMailnoreply');
$appModeregistrationterme = $this->getParameter('appModeregistrationterme');
// Génération de la date de fin de validité de la clé
$keyexpire=new \DateTime();
$keyexpire->add(new \DateInterval('PT'.$appModeregistrationterme.'H'));
// Enregistrement des valeurs
$user->setKeyvalue(Uuid::uuid4());
$user->setKeyexpire($keyexpire);
// Sauvegarde
$em->getManager()->flush();
// Email au user
$url = $this->generateUrl('app_resetpwd02', array("key"=>$user->getKeyvalue()), UrlGeneratorInterface::ABSOLUTE_URL);
$subject=$appname." : réinitialisation mot de passe";
$body="<p>Merci de réinitialiser votre mot de passe en cliquant sur le lien suivant</p><p><a href='".$url."'>".$url."</a></p><br><p>Attention vous disposez dun délai de ".$appModeregistrationterme." heures pour le faire.</p><p>Vous pourrez par la suite vous connecter avec votre login : ".$user->getUsername()."</p>";
$to = $user->getEmail();
$from = $noreply;
$fromName = $appname;
$this->mail->sendEmail($subject, $body, $to, $from, $fromName);
// Info
$info="Vous allez recevoir un mail avec lien qui vous permettra de réinitialiser votre mot de passe";
$mode="info";
$request->getSession()->set('registrationinfo', $info);
$request->getSession()->set('registrationmode', $mode);
$request->getSession()->set('registrationredirectto', null);
return $this->redirectToRoute('app_registration_info');
}
// Affichage du formulaire
return $this->render($this->twig.'resetpwd01.html.twig', [
'useheader' => true,
'usemenu' => false,
'usesidebar' => false,
'maxsize' => 1200,
'form' => $form->createView()
]);
}
public function resetpwd02($key,Request $request,ManagerRegistry $em)
{
$appMasteridentity = $this->getParameter('appMasteridentity');
if($appMasteridentity!="SQL")
throw $this->createAccessDeniedException('Permission denied');
$now=new \DateTime();
$user = $em ->getManager()->createQueryBuilder()
->select('table')
->from("App:User",'table')
->where('table.keyvalue= :key')
->andWhere('table.keyexpire >= :date')
->setParameter("key", $key)
->setParameter("date", $now)
->getQuery()
->getSingleResult();
if(!$user) {
$info="Clé de validation invalide";
$mode="danger";
$request->getSession()->set('registrationinfo', $info);
$request->getSession()->set('registrationmode', $mode);
$request->getSession()->set('registrationredirectto', null);
return $this->redirectToRoute('app_registration_info');
}
else {
// Création du formulaire
$form = $this->createForm(ResetpwdType::class,$user,array("mode"=>"resetpwd02"));
// Récupération des data du formulaire
$form->handleRequest($request);
if ($form->get('submit')->isClicked() && $form->isValid()) {
$data = $form->getData();
$user->setKeyvalue(null);
$user->setKeyexpire(null);
$user->setPassword($data->getPassword());
// Sauvegarde
$em->getManager()->flush();
$url=$this->generateUrl('app_login');
$info="<p>Nouveau mot de passe prise en compte</p><p>Vous allez être redirigé vers la mire de connexion</p><p><a href='".$url."'>Connexion</a>";
$mode="success";
$request->getSession()->set('registrationinfo', $info);
$request->getSession()->set('registrationmode', $mode);
$request->getSession()->set('registrationredirectto', null);
return $this->redirectToRoute('app_registration_info');
}
// Affichage du formulaire
return $this->render($this->twig.'resetpwd02.html.twig', [
'useheader' => true,
'usemenu' => false,
'usesidebar' => false,
'maxsize' => 1200,
'form' => $form->createView()
]);
}
}
private function canupdate($access,$entity,$em) {
switch($access) {
case "admin" : return true; break;
case "modo" :
$usermodo=$em->getRepository("App\Entity\UserModo")->findOneBy(["user"=>$this->getUser(),"niveau01"=>$entity->getNiveau01()]);
if(!$usermodo) throw $this->createAccessDeniedException('Permission denied');
return true;
break;
}
throw $this->createAccessDeniedException('Permission denied');
}
private function candelete($access,$entity,$em) {
switch($access) {
case "admin" : return true; break;
case "modo" :
$usermodo=$em->getRepository("App\Entity\UserModo")->findOneBy(["user"=>$this->getUser(),"niveau01"=>$entity->getNiveau01()]);
if(!$usermodo) throw $this->createAccessDeniedException('Permission denied');
return true;
break;
}
throw $this->createAccessDeniedException('Permission denied');
}
protected function getErrorForm($id,$form,$request,$data,$mode,$idstatut) {
if ($form->get('submit')->isClicked() && $mode=="submit") {
// Si validation par administrateur demander une motivation
$appmoderegistration = $this->getParameter('appModeregistration');
if(is_null($data->getMotivation())&&$appmoderegistration=="byadmin") {
// On recherche le domaine du mail dans la liste blanche
$email=explode("@",$data->getEmail());
$domaine=end($email);
$whitelist = $this->getDoctrine()->getManager()->getRepository("App\Entity\Whitelist")->findBy(["label"=>$domaine]);
if(!$whitelist)
$form->addError(new FormError("Attention, le suffixe de votre adresse mail nest pas dans la liste des administrations autorisées, merci de bien vouloir privilégier votre adresse professionnelle si vous en avez une.<br>Si ce nest pas le cas, il faut que vous renseigniez la case motivation de votre demande"));
}
}
if ($form->get('submit')->isClicked() && !$form->isValid()) {
$errors = $form->getErrors();
foreach( $errors as $error ) {
$request->getSession()->getFlashBag()->add("error", $error->getMessage());
$request->getSession()->getFlashBag()->add("error", $error->getMessage());
}
}
}
}

View File

@ -0,0 +1,468 @@
<?php
namespace App\Controller;
use FOS\RestBundle\Controller\AbstractFOSRestController;
use Symfony\Component\HttpFoundation\Request;
use FOS\RestBundle\Controller\Annotations as FOSRest;
use OpenApi\Annotations as OA;
use Doctrine\Persistence\ManagerRegistry;
class RestController extends AbstractFOSRestController
{
private $output=[];
private $cpt;
/**
* getAllUsers
*
*
* @FOSRest\Get("/rest/getAllUsers")
* @OA\Response(
* response=200,
* description="get all users"
* )
* )
* @OA\Parameter(
* name="key",
* in="header",
* required=true,
* description="APIKey",
* @OA\Schema(type="string")
* )
*/
public function getAllUsers(Request $request,ManagerRegistry $em) {
set_time_limit(0);
ini_set('memory_limit', '1024M');
// Récupération des parametres
if(!$this->iskey($request->headers->get("key"))) {
$view = $this->view("API Key inconnue", 403);
return $this->handleView($view);
}
$output = [];
$users=$em->getRepository("App\Entity\User")->findAll();
foreach($users as $user) {
array_push($output,$this->userFormat($user));
}
$view = $this->view($output, 200);
return $this->handleView($view);
}
/**
* getOneUser
*
*
* @FOSRest\Get("/rest/getOneUser")
* @OA\Response(
* response=200,
* description="get one user by login"
* )
* )
* @OA\Parameter(
* name="key",
* in="header",
* required=true,
* description="APIKey",
* @OA\Schema(type="string")
* )
* @OA\Parameter(
* name="login",
* in="header",
* required=true,
* description="Login",
* @OA\Schema(type="string")
* )
*/
public function getOneUser(Request $request,ManagerRegistry $em) {
set_time_limit(0);
ini_set('memory_limit', '1024M');
// Récupération des parametres
if(!$this->iskey($request->headers->get("key"))) {
$view = $this->view("API Key inconnue", 403);
return $this->handleView($view);
}
$output = [];
$user=$em->getRepository("App\Entity\User")->findOneBy(["username"=>$request->headers->get("login")]);
if(!$user) {
$view = $this->view("Utilisateur inconnue", 403);
return $this->handleView($view);
}
$output=$this->userFormat($user);
$view = $this->view($output, 200);
return $this->handleView($view);
}
/**
* getAllNiveau01s
*
*
* @FOSRest\Get("/rest/getAllNiveau01s")
* @OA\Response(
* response=200,
* description="get all niveau01"
* )
* )
* @OA\Parameter(
* name="key",
* in="header",
* required=true,
* description="APIKey",
* @OA\Schema(type="string")
* )
*/
public function getAllNiveau01s(Request $request,ManagerRegistry $em) {
set_time_limit(0);
ini_set('memory_limit', '1024M');
// Récupération des parametres
if(!$this->iskey($request->headers->get("key"))) {
$view = $this->view("API Key inconnue", 403);
return $this->handleView($view);
}
$output = [];
$niveau01s=$em->getRepository("App\Entity\Niveau01")->findAll();
foreach($niveau01s as $niveau01) {
array_push($output,$this->niveau01Format($niveau01,true));
}
$view = $this->view($output, 200);
return $this->handleView($view);
}
/**
* getOneNiveau01
*
*
* @FOSRest\Get("/rest/getOneNiveau01")
* @OA\Response(
* response=200,
* description="get one niveau01 by label"
* )
* )
* @OA\Parameter(
* name="key",
* in="header",
* required=true,
* description="APIKey",
* @OA\Schema(type="string")
* )
* @OA\Parameter(
* name="label",
* in="header",
* required=true,
* description="Label",
* @OA\Schema(type="string")
* )
*/
public function getOneNiveau01(Request $request,ManagerRegistry $em) {
set_time_limit(0);
ini_set('memory_limit', '1024M');
// Récupération des parametres
if(!$this->iskey($request->headers->get("key"))) {
$view = $this->view("API Key inconnue", 403);
return $this->handleView($view);
}
$output = [];
$niveau01=$em->getRepository("App\Entity\Niveau01")->findOneBy(["label"=>$request->headers->get("label")]);
if(!$niveau01) {
$view = $this->view("Niveau01 inconnu", 403);
return $this->handleView($view);
}
$output=$this->niveau01Format($niveau01,true);
$view = $this->view($output, 200);
return $this->handleView($view);
}
/**
* getAllNiveau02s
*
*
* @FOSRest\Get("/rest/getAllNiveau02s")
* @OA\Response(
* response=200,
* description="get all niveau02"
* )
* )
* @OA\Parameter(
* name="key",
* in="header",
* required=true,
* description="APIKey",
* @OA\Schema(type="string")
* )
*/
public function getAllNiveau02s(Request $request,ManagerRegistry $em) {
set_time_limit(0);
ini_set('memory_limit', '1024M');
// Récupération des parametres
if(!$this->iskey($request->headers->get("key"))) {
$view = $this->view("API Key inconnue", 403);
return $this->handleView($view);
}
$output = [];
$niveau02s=$em->getRepository("App\Entity\Niveau02")->findAll();
foreach($niveau02s as $niveau02) {
array_push($output,$this->niveau02Format($niveau02,true));
}
$view = $this->view($output, 200);
return $this->handleView($view);
}
/**
* getOneNiveau02
*
*
* @FOSRest\Get("/rest/getOneNiveau02")
* @OA\Response(
* response=200,
* description="get one niveau02 by label"
* )
* )
* @OA\Parameter(
* name="key",
* in="header",
* required=true,
* description="APIKey",
* @OA\Schema(type="string")
* )
* @OA\Parameter(
* name="label",
* in="header",
* required=true,
* description="Label",
* @OA\Schema(type="string")
* )
*/
public function getOneNiveau02(Request $request,ManagerRegistry $em) {
set_time_limit(0);
ini_set('memory_limit', '1024M');
// Récupération des parametres
if(!$this->iskey($request->headers->get("key"))) {
$view = $this->view("API Key inconnue", 403);
return $this->handleView($view);
}
$output = [];
$niveau02=$em->getRepository("App\Entity\Niveau02")->findOneBy(["label"=>$request->headers->get("label")]);
if(!$niveau02) {
$view = $this->view("Niveau02 inconnu", 403);
return $this->handleView($view);
}
$output=$this->niveau02Format($niveau02,true);
$view = $this->view($output, 200);
return $this->handleView($view);
}
/**
* getAllGroups
*
*
* @FOSRest\Get("/rest/getAllGroups")
* @OA\Response(
* response=200,
* description="get all group"
* )
* )
* @OA\Parameter(
* name="key",
* in="header",
* required=true,
* description="APIKey",
* @OA\Schema(type="string")
* )
*/
public function getAllGroups(Request $request,ManagerRegistry $em) {
set_time_limit(0);
ini_set('memory_limit', '1024M');
// Récupération des parametres
if(!$this->iskey($request->headers->get("key"))) {
$view = $this->view("API Key inconnue", 403);
return $this->handleView($view);
}
$output = [];
$groups=$em->getRepository("App\Entity\Group")->findAll();
foreach($groups as $group) {
if($group->getId()<0) continue;
array_push($output,$this->groupFormat($group,true));
}
$view = $this->view($output, 200);
return $this->handleView($view);
}
/**
* getOneGroup
*
*
* @FOSRest\Get("/rest/getOneGroup")
* @OA\Response(
* response=200,
* description="get one group by label"
* )
* )
* @OA\Parameter(
* name="key",
* in="header",
* required=true,
* description="APIKey",
* @OA\Schema(type="string")
* )
* @OA\Parameter(
* name="label",
* in="header",
* required=true,
* description="Label",
* @OA\Schema(type="string")
* )
*/
public function getOneGroup(Request $request,ManagerRegistry $em) {
set_time_limit(0);
ini_set('memory_limit', '1024M');
// Récupération des parametres
if(!$this->iskey($request->headers->get("key"))) {
$view = $this->view("API Key inconnue", 403);
return $this->handleView($view);
}
$output = [];
$group=$em->getRepository("App\Entity\Group")->findOneBy(["label"=>$request->headers->get("label")]);
if(!$group) {
$view = $this->view("Group inconnu", 403);
return $this->handleView($view);
}
$output=$this->groupFormat($group,true);
$view = $this->view($output, 200);
return $this->handleView($view);
}
private function iskey($key) {
return ($key==$this->getParameter("appSecret"));
}
private function userFormat($user) {
$output=[];
$output["userid"]=$user->getId();
$output["userlogin"]=$user->getUsername();
$output["userlastname"]=$user->getLastname();
$output["userfirstname"]=$user->getFirstname();
$output["useremail"]=$user->getEmail();
$output["userjob"]=$user->getJob();
$output["userposition"]=$user->getPosition();
$output["userpostaladress"]=$user->getPostaladress();
$output["usertelephonenumber"]=$user->getTelephonenumber();
if(stripos($user->getAvatar(),"http")===0) $output["useravatar"]=$user->getAvatar();
else $output["useravatar"]="https://".$this->getParameter("appWeburl").$this->getParameter("appAlias")."uploads/avatar/".$user->getAvatar();
$output["userniveau01"]=$this->niveau01Format($user->getNiveau01());
$output["userniveau02"]=$this->niveau02Format($user->getNiveau02());
$output["usergroups"]=[];
foreach($user->getGroups() as $usergroup) {
$groupFormat=$this->groupFormat($usergroup->getGroup());
if($groupFormat) array_push($output["usergroups"],$groupFormat);
}
if(empty($output["usergroups"])) $output["usergroups"]=null;
return $output;
}
private function niveau01Format($niveau01,$withmembers=false){
if(!$niveau01) return null;
$output=[];
$output["niveau01id"]=$niveau01->getId();
$output["niveau01label"]=$niveau01->getLabel();
if($withmembers) {
$output["niveau01users"]=[];
foreach($niveau01->getUsers() as $user) {
array_push($output["niveau01users"],["userid"=>$user->getId(),"userlogin"=>$user->getUsername()]);
}
if(empty($output["niveau01users"])) $output["niveau01users"]=null;
}
return $output;
}
private function niveau02Format($niveau02,$withmembers=false){
if(!$niveau02) return null;
$output=[];
$output["niveau02id"]=$niveau02->getId();
$output["niveau02label"]=$niveau02->getLabel();
if($withmembers) {
$output["niveau02niveau01"]=$this->niveau01Format($niveau02->getNiveau01());
$output["niveau02users"]=[];
foreach($niveau02->getUsers() as $user) {
array_push($output["niveau02users"],["userid"=>$user->getId(),"userlogin"=>$user->getUsername()]);
}
if(empty($output["niveau02users"])) $output["niveau02users"]=null;
}
return $output;
}
private function groupFormat($group,$withmembers=false){
if(!$group||$group->getId()<0) return null;
$output=[];
$output["groupid"]=$group->getId();
$output["grouplabel"]=$group->getLabel();
if($withmembers) {
$output["groupusers"]=[];
foreach($group->getUsers() as $usergroup) {
array_push($output["groupusers"],["userid"=>$usergroup->getUser()->getId(),"userlogin"=>$usergroup->getUser()->getUsername()]);
}
if(empty($output["groupusers"])) $output["groupusers"]=null;
}
return $output;
}
}

View File

@ -0,0 +1,496 @@
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\HttpKernel\KernelInterface;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Ramsey\Uuid\Uuid;
use App\Entity\User;
use App\Entity\Niveau01;
use App\Entity\Group;
use App\Form\LoginType;
use App\Service\LdapService;
use App\Service\ApiService;
class SecurityController extends AbstractController
{
private $appKernel;
private $tokenstorage;
private $ldapservice;
private $apiservice;
public function __construct(KernelInterface $appKernel, TokenStorageInterface $tokenstorage, LdapService $ldapservice, ApiService $apiservice)
{
$this->appKernel = $appKernel;
$this->tokenstorage = $tokenstorage;
$this->ldapservice = $ldapservice;
$this->apiservice = $apiservice;
}
public function login(Request $request, AuthenticationUtils $authenticationUtils,ManagerRegistry $em)
{
switch($this->getParameter("appAuth")) {
case "SQL":
return $this->loginSQL($request,$authenticationUtils,$em);
break;
case "CAS":
return $this->loginCAS($request,$authenticationUtils,$em);
break;
case "LDAP":
return $this->loginLDAP($request,$authenticationUtils,$em);
break;
case "OPENID":
return $this->loginOPENID($request,$authenticationUtils,$em);
break;
}
}
public function loginSQL(Request $request, AuthenticationUtils $authenticationUtils)
{
return $this->render('Home/loginSQL.html.twig', array(
'last_username' => $authenticationUtils->getLastUsername(),
'error' => $authenticationUtils->getLastAuthenticationError(),
));
}
public function loginCAS(Request $request, AuthenticationUtils $authenticationUtils,ManagerRegistry $em)
{
// Récupération de la cible de navigation
$redirect = $request->getSession()->get("_security.main.target_path");
// Masteridentity
$appMasteridentity=$this->getParameter("appMasteridentity");
// Init Client CAS
$alias=$this->getParameter('appAlias');
\phpCAS::setDebug($this->appKernel->getProjectDir()."/var/log/cas.log");
\phpCAS::client(CAS_VERSION_2_0, $this->getParameter('casHost'), intval($this->getParameter('casPort')), is_null($this->getParameter('casPath')) ? '' : $this->getParameter('casPath'), false);
\phpCAS::setNoCasServerValidation();
// Authentification
\phpCAS::forceAuthentication();
// Récupération UID
$username = \phpCAS::getUser();
// Récupération Attribut
$attributes = \phpCAS::getAttributes();
// Init
$email = "$username@nomail.fr";
$lastname = $username;
$firstname = " ";
$avatar="noavatar.png";
// Rechercher l'utilisateur
if(isset($attributes[$this->getParameter('casUsername')]))
$username = $attributes[$this->getParameter('casUsername')];
if(isset($attributes[$this->getParameter('casEmail')]))
$email = $attributes[$this->getParameter('casEmail')];
if(isset($attributes[$this->getParameter('casLastname')]))
$lastname = $attributes[$this->getParameter('casLastname')];
if(isset($attributes[$this->getParameter('casFirstname')]))
$firstname = $attributes[$this->getParameter('casFirstname')];
if(isset($attributes[$this->getParameter('casAvatar')]))
$avatar = $attributes[$this->getParameter('casAvatar')];
// Génération auto des niveau01s et des groupes en fonction des attributs sso
$this->submitSSONiveau01($attributes,$em);
$this->submitSSOGroup($attributes,$em);
// Rechercher l'utilisateur
$user = $em->getRepository('App\Entity\User')->findOneBy(array("username"=>$username));
if (!$user) {
$niveau01=$em->getRepository('App\Entity\Niveau01')->calculateSSONiveau01($attributes);
$user=$this->submituser($username,$firstname,$lastname,$email,$password,$niveau01,$em);
}
else
$this->updateuser($user,$firstname,$lastname,$email,$avatar,$em);
// On calcule les groupes de l'utilisateur
$user=$em->getRepository('App\Entity\Group')->calculateSSOGroup($user,$attributes);
// Autoconnexion
return $this->autoconnexion($user,$redirect,$request);
}
public function loginLDAP(Request $request)
{
// Création du formulaire
$form = $this->createForm(LoginType::class);
// Récupération des data du formulaire
$form->handleRequest($request);
// Affichage du formulaire
return $this->render("Home/loginLDAP.html.twig", [
"useheader"=>false,
"usemenu"=>false,
"usesidebar"=>false,
"form"=>$form->createView(),
]);
}
public function loginldapcheck(Request $request, AuthenticationUtils $authenticationUtils,ManagerRegistry $em)
{
$username=$request->get('login')["username"];
$password=$request->get('login')["password"];
$appMasteridentity=$this->getParameter("appMasteridentity");
// Récupération de la cible de navigation
$redirect = $request->getSession()->get("_security.main.target_path");
// L'utilisateur se co à l'annuaire
$userldap=$this->ldapservice->userconnect($username,$password);
if($userldap) {
$userldap=$userldap[0];
// Init
$email = "$username@nomail.fr";
$lastname = $username;
$firstname = " ";
$avatar="noavatar.png";
// Rechercher l'utilisateur
if(isset($userldap[$this->getParameter('ldapFirstname')]))
$firstname = $userldap[$this->getParameter('ldapFirstname')];
if(isset($userldap[$this->getParameter('ldapLastname')]))
$lastname = $userldap[$this->getParameter('ldapLastname')];
if(isset($userldap[$this->getParameter('ldapEmail')]))
$email = $userldap[$this->getParameter('ldapEmail')];
if(isset($userldap[$this->getParameter('ldapAvatar')]))
$avatar = $userldap[$this->getParameter('ldapAvatar')];
$user = $em->getRepository('App\Entity\User')->findOneBy(array("username"=>$username));
if (!$user) {
$niveau01=$em->getRepository('App\Entity\Niveau01')->calculateLDAPNiveau01($username);
$user=$this->submituser($username,$firstname,$lastname,$email,$avatar,$niveau01,$em);
}
else {
$this->updateuser($user,$firstname,$lastname,$email,$avatar,$em);
}
// Autoconnexion
return $this->autoconnexion($user,$redirect,$request);
}
return $this->redirect($this->generateUrl('app_login'));
}
public function loginOPENID(Request $request, AuthenticationUtils $authenticationUtils)
{
$callback=$this->generateUrl('app_loginopenidcallback', array(), UrlGeneratorInterface::ABSOLUTE_URL);
$url=$this->getParameter("oauthLoginurl")."?client_id=".$this->getParameter("oauthClientid")."&redirect_uri=".$callback."&response_type=code&state=STATE&scope=openid";
return $this->redirect($url);
}
public function loginopenidcallback(Request $request, AuthenticationUtils $authenticationUtils,ManagerRegistry $em)
{
// Récupération de la cible de navigation
$redirect = $request->getSession()->get("_security.main.target_path");
// Masteridentity
$appMasteridentity=$this->getParameter("appMasteridentity");
$callback=$this->generateUrl('app_loginopenidcallback', array(), UrlGeneratorInterface::ABSOLUTE_URL);
$apiurl = $this->getParameter("oauthTokenurl");
$query= [
"grant_type" => "authorization_code",
"code" => $request->get("code"),
"redirect_uri" => $callback,
"client_id" => $this->getParameter("oauthClientid"),
"client_secret" => $this->getParameter("oauthClientsecret"),
];
$response=$this->apiservice->run("POST",$apiurl,$query);
if(!$response||$response->code!="200") return $this->logout($request);
$token=$response->body->access_token;
$request->getSession()->set("oauthToken",$token);
$apiurl = $this->getParameter("oauthUserinfo");
$response=$this->apiservice->run("GET",$apiurl,null,["Authorization"=>"token ".$token]);
if(!$response||$response->code!="200") return $this->logout($request);
$attributes=json_decode(json_encode($response->body), true);
// Username
if(isset($attributes[$this->getParameter('oauthUsername')]))
$username = $attributes[$this->getParameter('oauthUsername')];
// Valeur par défaut
$email = "$username@nomail.fr";
$lastname = $username;
$firstname = " ";
$avatar="noavatar.png";
// Récupérer les attributs associés
if(isset($attributes[$this->getParameter('oauthEmail')]))
$email = $attributes[$this->getParameter('oauthEmail')];
if(isset($attributes[$this->getParameter('oauthLastname')]))
$lastname = $attributes[$this->getParameter('oauthLastname')];
if(isset($attributes[$this->getParameter('oauthFirstname')]))
$firstname = $attributes[$this->getParameter('oauthFirstname')];
if(isset($attributes[$this->getParameter('oauthAvatar')]))
$avatar = $attributes[$this->getParameter('oauthAvatar')];
// Génération auto des niveau01s et des groupes en fonction des attributs sso
$this->submitSSONiveau01($attributes,$em);
$this->submitSSOGroup($attributes,$em);
// Rechercher l'utilisateur
$user = $em->getRepository('App\Entity\User')->findOneBy(array("username"=>$username));
if (!$user) {
$niveau01=$em->getRepository('App\Entity\Niveau01')->calculateSSONiveau01($attributes);
$user=$this->submituser($username,$firstname,$lastname,$email,$avatar,$niveau01,$em);
}
else
$this->updateuser($user,$firstname,$lastname,$email,$avatar,$em);
// On calcule les groupes de l'utilisateur
$user=$em->getRepository('App\Entity\Group')->calculateSSOGroup($user,$attributes);
// Autoconnexion
return $this->autoconnexion($user,$redirect,$request);
}
public function logout(Request $request) {
$auth_mode=$this->getParameter("appAuth");
switch($auth_mode) {
case "SQL":
return $this->logoutSQL($request);
break;
case "CAS":
return $this->logoutCAS($request);
break;
case "LDAP":
return $this->logoutLDAP($request);
break;
case "OPENID":
return $this->logoutOPENID($request);
break;
}
}
public function logoutSQL(Request $request) {
$this->tokenstorage->setToken(null);
$request->getSession()->invalidate();
return $this->redirect($this->generateUrl("app_home"));
}
public function logoutCAS(Request $request) {
$this->tokenstorage->setToken(null);
$request->getSession()->invalidate();
// Init Client CAS
$alias=$this->getParameter('appAlias');
\phpCAS::setDebug($this->appKernel->getProjectDir()."/var/log/cas.log");
\phpCAS::client(CAS_VERSION_2_0, $this->getParameter('casHost'), intval($this->getParameter('casPort')), is_null($this->getParameter('casPath')) ? '' : $this->getParameter('casPath'), false);
\phpCAS::setNoCasServerValidation();
// Logout
$url=$this->generateUrl('app_home', array(), UrlGeneratorInterface::ABSOLUTE_URL);
\phpCAS::logout(array("service"=>$url));
return true;
}
public function logoutLDAP(Request $request) {
$this->tokenstorage->setToken(null);
$request->getSession()->invalidate();
return $this->redirect($this->generateUrl("app_home"));
}
public function logoutOPENID(Request $request) {
$token=$request->getSession()->get("oauthToken");
$this->tokenstorage->setToken(null);
$request->getSession()->invalidate();
$url=$this->getParameter("oauthLogouturl");
if($url) {
$url.="?id_token_hint=$token&state=openid&post_logout_redirect_uri=http://127.0.0.1:8000";
return $this->redirect($url);
} else return $this->redirect($this->generateUrl("app_home"));
}
// Génération automatique des niveau01 provenant de l'attribut casniveau01
private function submitSSONiveau01($attributes,ManagerRegistry $em) {
$attrNiveau01=($this->getParameter("appAuth")=="CAS"?$this->getParameter('casNiveau01'):$this->getParameter('oauthNiveau01'));
if(!$attrNiveau01)
return null;
// Si l'utilisateur possège l'attribut niveau01 dans ses attributs
if(array_key_exists($attrNiveau01,$attributes)) {
if(!is_array($attributes[$attrNiveau01])) {
$attributes[$attrNiveau01]=[$attributes[$attrNiveau01]];
}
foreach($attributes[$attrNiveau01] as $ssoniveau01) {
$basedn=$this->getParameter('ldapBasedn');
$name=$ssoniveau01;
if($basedn!="") {
// Si présence du basedn dans le nom du groupe = nous sommes en présence d'un DN = on récupere donc comme nom que son cn
if(stripos($name,$basedn)!==false) {
$tbname=explode(",",$name);
$tbname=explode("=",$tbname[0]);
$name=$tbname[1];
}
}
// Recherche du groupe
$niveau01=$em->getRepository("App\Entity\Niveau01")->findOneBy(["label"=>$name]);
if(!$niveau01) {
$niveau01=new Niveau01();
$niveau01->setLabel($name);
$niveau01->setApikey(Uuid::uuid4());
}
$niveau01->setAttributes('{"'.$attrNiveau01.'":"'.$ssoniveau01.'"}');
$em->getManager()->persist($niveau01);
$em->getManager()->flush();
}
}
}
// Génération automatique des groupes provenant de l'attribut casgroup ou oauthgroup
private function submitSSOGroup($attributes,ManagerRegistry $em) {
$attrGroup=($this->getParameter("appAuth")=="CAS"?$this->getParameter('casGroup'):$this->getParameter('oauthGroup'));
if(!$attrGroup)
return null;
// Si l'utilisateur possège l'attribut groupe dans ses attributs
if(array_key_exists($attrGroup,$attributes)) {
if(!is_array($attributes[$attrGroup])) {
$attributes[$attrGroup]=[$attributes[$attrGroup]];
}
foreach($attributes[$attrGroup] as $ssogroup) {
$basedn=$this->getParameter('ldapBasedn');
$name=$ssogroup;
if($basedn!="") {
// Si présence du basedn dans le nom du groupe = nous sommes en présence d'un DN = on récupere donc comme nom que son cn
if(stripos($name,$basedn)!==false) {
$tbname=explode(",",$name);
$tbname=explode("=",$tbname[0]);
$name=$tbname[1];
}
}
// Recherche du groupe
$group=$em->getRepository("App\Entity\Group")->findOneBy(["label"=>$name]);
if(!$group) {
$group=new Group();
$group->setLabel($name);
$group->setIsopen(false);
$group->setIsworkgroup(false);
$group->setApikey(Uuid::uuid4());
}
$group->setAttributes('{"'.$attrGroup.'":"'.$ssogroup.'"}');
$em->getManager()->persist($group);
$em->getManager()->flush();
}
}
}
private function submituser($username,$firstname,$lastname,$email,$avatar,$niveau01,$em) {
if(empty($email)) $email = $username."@nomail.com";
if(empty($avatar)) $avatar = "noavatar.png";
if(empty($firstname)) $firstname = " ";
if(empty($lastname)) $lastname = $username;
$password=$this->getParameter("appAuth")."PWD-".$username;
// Si aucun niveau01 on prend par défaut le niveau system
if(!$niveau01) $niveau01=$em->getRepository('App\Entity\Niveau01')->find(-1);
// Autogénération du user vu qu'il a pu se connecter
$user = new User();
$user->setUsername($username);
$user->setEmail($email);
$user->setLastname($lastname);
$user->setFirstname($firstname);
$user->setApikey(Uuid::uuid4());
$user->setPassword($password);
$user->setNiveau01($niveau01);
$user->setAvatar($avatar);
$user->setIsvisible(true);
$user->setRole("ROLE_USER");
if(in_array($username,$this->getParameter("appAdmins")))
$user->setRole("ROLE_ADMIN");
$em->getManager()->persist($user);
$em->getManager()->flush();
return $user;
}
private function updateuser($user,$firstname,$lastname,$email,$avatar,$em) {
if($avatar=="noavatar.png") $avatar=$user->getAvatar();
if(!empty($lastname)) $user->setLastname($lastname);
if(!empty($firstname)) $user->setFirstname($firstname);
if(!empty($email)) $user->setEmail($email);
if(!empty($avatar)) $user->setAvatar($avatar);
if(in_array($user->getUsername(),$this->getParameter("appAdmins")))
$user->setRole("ROLE_ADMIN");
$em->getManager()->flush();
}
private function autoconnexion($user,$redirect,Request $request)
{
// Récupérer le token de l'utilisateur
$token = new UsernamePasswordToken($user, "main", $user->getRoles());
$this->tokenstorage->setToken($token);
$request->getSession()->set('_security_main', serialize($token));
// Simuler l'evenement de connexion
$event = new InteractiveLoginEvent($request, $token);
$dispatcher = new EventDispatcher();
$dispatcher->dispatch($event);
// Redirection
if($redirect)
return $this->redirect($redirect);
else
return $this->redirect($this->generateUrl('app_home'));
}
}

View File

@ -0,0 +1,670 @@
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Doctrine\Persistence\ManagerRegistry;
use Ramsey\Uuid\Uuid;
use App\Entity\User as Entity;
use App\Entity\UserGroup;
use App\Entity\UserModo;
use App\Form\UserType as Form;
class UserController extends AbstractController
{
private $data="user";
private $entity="App\Entity\User";
private $twig="User/";
private $route="app_admin_user";
public function list($access,Request $request): Response
{
if($access=="user"&&!$request->getSession()->get("showannuaire"))
throw $this->createAccessDeniedException('Permission denied');
return $this->render($this->twig.'list.html.twig',[
"useheader"=>true,
"usemenu"=>false,
"usesidebar"=>($access!="user"),
"access"=>$access
]);
}
public function tablelist($access, Request $request,ManagerRegistry $em): Response
{
$query=$request->query->all();
$start=$query['start'];
$length=$query['length'];
$search=$query['search'];
$draw= $query['draw'];
$ordercolumn=$query['order'][0]['column'];
$orderdir=$query['order'][0]['dir'];
// Nombre total d'enregistrement
switch($access) {
case "admin":
$total = $em->getManager()->createQueryBuilder()->select('COUNT(entity)')->from($this->entity,'entity')->getQuery()->getSingleScalarResult();
break;
case "modo":
$total = $em->getManager()->createQueryBuilder()
->select('COUNT(entity)')
->from($this->entity,'entity')
->from("App\Entity\UserModo",'usermodo')
->where("usermodo.niveau01 = entity.niveau01")
->andWhere("usermodo.user = :user")
->setParameter("user", $this->getUser())
->getQuery()->getSingleScalarResult();
break;
default:
$niveau01=$this->getUser()->getNiveau01();
$niveau02=$this->getUser()->getNiveau02();
$qb=$em->getManager()->createQueryBuilder()->select('COUNT(entity)')->from($this->entity,'entity')->where('entity.isvisible=true');
switch($request->getSession()->get("scopeannu")) {
case "SAME_NIVEAU01":
$qb->andWhere("entity.niveau01 = :niveau01")->setParameter("niveau01",$niveau01);
break;
case "SAME_NIVEAU02":
$qb->andWhere("entity.niveau02 = :niveau02")->setParameter("niveau02",$niveau02);
break;
}
$total = $qb->getQuery()->getSingleScalarResult();
break;
}
// Nombre d'enregistrement filtré
if(!$search||$search["value"]=="")
$totalf = $total;
else {
switch($access) {
case "admin":
$totalf= $em->getManager()->createQueryBuilder()
->select('COUNT(entity)')
->from($this->entity,'entity')
->from('App:Niveau01', 'niveau01')
->where('entity.niveau01=niveau01.id')
->andWhere('entity.username LIKE :value OR entity.firstname LIKE :value OR entity.lastname LIKE :value OR entity.email LIKE :value OR entity.roles LIKE :value OR niveau01.label LIKE :value')
->setParameter("value", "%".$search["value"]."%")
->getQuery()
->getSingleScalarResult();
break;
case "modo":
$totalf= $em->getManager()->createQueryBuilder()
->select('COUNT(entity)')
->from($this->entity,'entity')
->from('App:Niveau01', 'niveau01')
->from("App:UserModo",'usermodo')
->where('entity.niveau01=niveau01.id')
->andWhere('entity.username LIKE :value OR entity.firstname LIKE :value OR entity.lastname LIKE :value OR entity.email LIKE :value OR entity.roles LIKE :value OR niveau01.label LIKE :value')
->andWhere("usermodo.niveau01 = entity.niveau01")
->andWhere("usermodo.user = :userid")
->setParameter("value", "%".$search["value"]."%")
->setParameter("userid", $this->getUser()->getId())
->getQuery()
->getSingleScalarResult();
break;
default:
$qb = $em->getManager()->createQueryBuilder()
->select('COUNT(entity)')
->from($this->entity,'entity')
->from('App:Niveau01', 'niveau01')
->where('entity.niveau01=niveau01.id')
->andWhere('entity.isvisible=true')
->andWhere('entity.username LIKE :value OR entity.firstname LIKE :value OR entity.lastname LIKE :value OR entity.email LIKE :value OR entity.roles LIKE :value OR niveau01.label LIKE :value')
->setParameter("value", "%".$search["value"]."%");
switch($request->getSession()->get("scopeannu")) {
case "SAME_NIVEAU01":
$qb->andWhere("entity.niveau01 = :niveau01")->setParameter("niveau01",$niveau01);
break;
case "SAME_NIVEAU02":
$qb->andWhere("entity.niveau02 = :niveau02")->setParameter("niveau02",$niveau02);
break;
}
$totalf=$qb->getQuery()->getSingleScalarResult();
break;
}
}
// Construction du tableau de retour
$output = array(
'draw' => $draw,
'recordsFiltered' => $totalf,
'recordsTotal' => $total,
'data' => array(),
);
// Parcours des Enregistrement
$qb = $em->getManager()->createQueryBuilder();
switch($access) {
case "admin":
$qb->select('entity')->from($this->entity,'entity')->from('App:Niveau01','niveau01');
$qb->where('entity.niveau01=niveau01.id');
break;
case "modo":
$qb->select('entity')->from($this->entity,'entity')->from('App:Niveau01','niveau01')->from("App:UserModo",'usermodo');
$qb->where('entity.niveau01=niveau01.id');
$qb->andWhere("usermodo.niveau01 = entity.niveau01");
$qb->andWhere("usermodo.user = :userid");
$qb->setParameter("userid", $this->getUser()->getId());
break;
default:
$qb->select('entity')->from($this->entity,'entity')->from('App:Niveau01','niveau01');
$qb->where('entity.niveau01=niveau01.id');
$qb->andWhere('entity.isvisible=true');
switch($request->getSession()->get("scopeannu")) {
case "SAME_NIVEAU01":
$qb->andWhere("entity.niveau01 = :niveau01")->setParameter("niveau01",$niveau01);
break;
case "SAME_NIVEAU02":
$qb->andWhere("entity.niveau02 = :niveau02")->setParameter("niveau02",$niveau02);
break;
}
break;
}
if($search&&$search["value"]!="") {
$qb ->andWhere('entity.username LIKE :value OR entity.firstname LIKE :value OR entity.lastname LIKE :value OR entity.email LIKE :value OR entity.roles LIKE :value OR niveau01.label LIKE :value')
->setParameter("value", "%".$search["value"]."%");
}
if($ordercolumn) {
if($access=="admin"||$access=="modo") {
$ordercolumn=$ordercolumn-1;
}
switch($ordercolumn) {
case 1 :
$qb->orderBy('entity.username',$orderdir);
break;
case 2 :
$qb->orderBy('entity.lastname',$orderdir);
break;
case 3 :
$qb->orderBy('entity.firstname',$orderdir);
break;
case 4 :
$qb->orderBy('entity.email',$orderdir);
break;
case 5 :
$qb->orderBy('entity.telephonenumber',$orderdir);
break;
case 6 :
$qb->orderBy('niveau01.label',$orderdir);
break;
case 8 :
$qb->orderBy('entity.visitedate',$orderdir);
break;
case 9 :
$qb->orderBy('entity.roles',$orderdir);
break;
}
}
$datas=$qb->setFirstResult($start)->setMaxResults($length)->getQuery()->getResult();
foreach($datas as $data) {
// Action
$action = "";
switch($access) {
case "admin":
$action.="<a href='".$this->generateUrl($this->route.'_update', array('id'=>$data->getId()))."'><i class='fa fa-file fa-fw fa-2x'></i></a>";
break;
case "modo":
$action.="<a href='".$this->generateUrl(str_replace("_admin_","_modo_",$this->route).'_update', array('id'=>$data->getId()))."'><i class='fa fa-file fa-fw fa-2x'></i></a>";
break;
}
// Groupes
$groups="";
foreach($data->getGroups() as $usergroup) {
$groups.=$usergroup->getGroup()->getLabel()."<br>";
}
// Roles
$roles="";
foreach($data->getRoles() as $role) {
$roles.=$role."<br>";
}
$tmp=array();
if($access=="admin"||$access=="modo") array_push($tmp,$action);
if(stripos($data->getAvatar(),"http")===0)
array_push($tmp,"<img src='".$data->getAvatar()."' class='avatar'>");
else
array_push($tmp,"<img src='".$this->getParameter('appAlias')."uploads/avatar/".$data->getAvatar()."' class='avatar'>");
array_push($tmp,$data->getUsername());
array_push($tmp,$data->getLastname());
array_push($tmp,$data->getFirstname());
array_push($tmp,"<a href='mailto:".$data->getEmail()."'>".$data->getEmail()."</a>");
array_push($tmp,$data->getTelephonenumber());
array_push($tmp,$data->getNiveau01()->getLabel());
array_push($tmp,($data->getNiveau02()?$data->getNiveau02()->getLabel():""));
array_push($tmp,($data->getVisitedate()?$data->getVisitedate()->format("d/m/Y H:i")."<br>nb = ".$data->getVisitecpt():""));
array_push($tmp,$roles);
array_push($tmp,$groups);
array_push($output["data"],$tmp);
}
// Retour
return new JsonResponse($output);
}
public function selectlist($access, Request $request,ManagerRegistry $em): Response
{
$output=array();
$page_limit=$request->query->get('page_limit');
$q=$request->query->get('q');
$qb = $em->getManager()->createQueryBuilder();
$qb->select('entity')->from($this->entity,'entity')
->where('entity.username LIKE :value')
->setParameter("value", "%".$q."%")
->orderBy('entity.username');
$datas=$qb->setFirstResult(0)->setMaxResults($page_limit)->getQuery()->getResult();
foreach($datas as $data) {
array_push($output,array("id"=>$data->getId(),"text"=>$data->getUsername()));
}
$ret_string["results"]=$output;
$response = new JsonResponse($ret_string);
return $response;
}
public function submit($access, Request $request,ManagerRegistry $em): Response
{
// Vérifier que l'on puisse créer
if($this->getParameter("appMasteridentity")!="SQL" && $this->getParameter("appSynchroPurgeUser"))
throw $this->createNotFoundException('Permission denied');
// Controler les permissions
$this->cansubmit($access,$em);
// Initialisation de l'enregistrement
$data = new Entity();
$data->setAvatar("noavatar.png");
$data->setIsvisible(true);
$data->setApikey(Uuid::uuid4());
// Création du formulaire
$form = $this->createForm(Form::class,$data,array(
"mode"=>"submit",
"access"=>$access,
"userid"=>$this->getUser()->getId(),
"appMasteridentity"=>$this->GetParameter("appMasteridentity"),
"appNiveau01label"=>$this->GetParameter("appNiveau01label"),
"appNiveau02label"=>$this->GetParameter("appNiveau02label"),
));
// Récupération des data du formulaire
$form->handleRequest($request);
// Sur validation
if ($form->get('submit')->isClicked() && $form->isValid()) {
$data = $form->getData();
// S'assurer que les modos ne donne pas des ROLE_ADMIN ou ROLE_USER au user qu'il submit
if($access=="modo") {
$roles=$data->getRoles();
$roles=array_diff($roles,["ROLE_ADMIN","ROLE_MODO"]);
$data->setRoles($roles);
}
// On récupère les groupes et on cacule ceux à ajouter ou à supprimer
$lstgroups=array_filter(explode(",",$form->get("linkgroups")->getData()));
$lstmodos=array_filter(explode(",",$form->get("linkmodos")->getData()));
// Sauvegarde
$em->getManager()->persist($data);
$em->getManager()->flush();
// Ajout des groupes
foreach($lstgroups as $idgroup) {
$group=$em->getRepository("App\Entity\Group")->find($idgroup);
$usergroup=$em->getRepository('App\Entity\UserGroup')->findBy(["user"=>$data,"group"=>$group]);
if(!$usergroup) {
$usergroup= new UserGroup();
$usergroup->setUser($data);
$usergroup->setGroup($group);
$usergroup->setApikey(Uuid::uuid4());
$usergroup->setRolegroup(0);
$em->getManager()->persist($usergroup);
$em->getManager()->flush();
}
}
// Ajout des modos
foreach($lstmodos as $idmodo) {
$niveau01=$em->getRepository("App\Entity\Niveau01")->find($idmodo);
$usermodo=$em->getRepository('App\Entity\UserModo')->findBy(["user"=>$data,"niveau01"=>$niveau01]);
if(!$usermodo) {
$usermodo= new UserModo();
$usermodo->setUser($data);
$usermodo->setNiveau01($dataniveau01);
$em->getManager()->persist($usermodo);
$em->getManager()->flush();
}
}
// Retour à la liste
return $this->redirectToRoute(str_replace("_admin_","_".$access."_",$this->route));
}
// Affichage du formulaire
return $this->render($this->twig.'edit.html.twig', [
"useheader"=>true,
"usemenu"=>false,
"usesidebar"=>true,
"access"=>$access,
"mode"=>"submit",
"form"=>$form->createView(),
$this->data=>$data,
"listgroups"=>$this->getListGroups("admin",$em),
"listmodos"=> $this->getListModos($em)
]);
}
public function profil($access,Request $request,ManagerRegistry $em): Response
{
$id=$this->getUser()->getId();
return $this->update($access,$id,$request,$em);
}
public function update($access,$id,Request $request,ManagerRegistry $em): Response
{
// Initialisation de l'enregistrement
$data=$em->getRepository($this->entity)->find($id);
if (!$data) throw $this->createNotFoundException('Unable to find entity.');
// Controler les permissions
$this->canupdate($access,$data,$em);
// Récupération de l'ancien password
$oldpassword=$data->getPassword();
// Récuparation des groupes associés
$oldlstgroups=[];
foreach($data->getGroups() as $group){
$oldlstgroups[] = $group->getGroup()->getId();
}
// Récuparation des modos associés
$oldlstmodos=[];
foreach($data->getModos() as $modo){
$oldlstmodos[] = $modo->getNiveau01()->getId();
}
// Création du formulaire
$form = $this->createForm(Form::class,$data,array(
"mode"=>"update",
"access"=>$access,
"userid"=>$this->getUser()->getId(),
"appMasteridentity"=>$this->GetParameter("appMasteridentity"),
"appNiveau01label"=>$this->GetParameter("appNiveau01label"),
"appNiveau02label"=>$this->GetParameter("appNiveau02label"),
));
// Récupération des data du formulaire
$form->handleRequest($request);
// Sur validation
if ($form->get('submit')->isClicked() && $form->isValid()) {
$data = $form->getData();
// S'assurer que les modos ne donne pas des ROLE_ADMIN ou ROLE_USER au user qu'il update
if($access=="modo") {
$roles=$data->getRoles();
$roles=array_diff($roles,["ROLE_ADMIN","ROLE_MODO"]);
$data->setRoles($roles);
}
// Si pas de changement de password on replace l'ancien
if($data->getPassword()=="") {
$data->setPassword($oldpassword);
}
// Sinon on encode le nouveau
else {
$data->setPassword($data->getPassword());
}
// Sauvegarde
$em->getManager()->flush();
// On récupère les groupes et on cacule ceux à ajouter ou à supprimer
$lstgroups=array_filter(explode(",",$form->get("linkgroups")->getData()));
$removegroups=array_diff($oldlstgroups,$lstgroups);
$addgroups=array_diff($lstgroups,$oldlstgroups);
// Ajout des nouveaux groupes
foreach($addgroups as $idgroup) {
$group=$em->getRepository("App\Entity\Group")->find($idgroup);
$usergroup=$em->getRepository('App\Entity\UserGroup')->findOneBy(["user"=>$data,"group"=>$group]);
if(!$usergroup) {
$usergroup= new UserGroup();
$usergroup->setUser($data);
$usergroup->setGroup($group);
$usergroup->setApikey(Uuid::uuid4());
$usergroup->setRolegroup(0);
$em->getManager()->persist($usergroup);
$em->getManager()->flush();
}
}
// Suppression des groupes obsolètes
foreach($removegroups as $idgroup) {
$group=$em->getRepository("App\Entity\Group")->find($idgroup);
$usergroup=$em->getRepository('App\Entity\UserGroup')->findOneBy(["user"=>$data,"group"=>$group]);
if($usergroup) {
$em->getManager()->remove($usergroup);
$em->getManager()->flush();
}
}
// On récupère les modos et on cacule ceux à ajouter ou à supprimer
$linkmodos=array_filter(explode(",",$form->get("linkmodos")->getData()));
$removemodos=array_diff($oldlstmodos,$linkmodos);
$addmodos=array_diff($linkmodos,$oldlstmodos);
// Ajout des nouveaux modos
foreach($addmodos as $idmodo) {
$niveau01=$em->getRepository("App\Entity\Niveau01")->find($idmodo);
$usermodo=$em->getRepository('App\Entity\UserModo')->findOneBy(["user"=>$data,"niveau01"=>$niveau01]);
if(!$usermodo) {
$usermodo= new UserModo();
$usermodo->setUser($data);
$usermodo->setNiveau01($niveau01);
$em->getManager()->persist($usermodo);
$em->getManager()->flush();
}
}
// Suppression des modos obsolètes
foreach($removemodos as $idmodo) {
$niveau01=$em->getRepository("App\Entity\Niveau01")->find($idmodo);
$usermodo=$em->getRepository('App\Entity\UserModo')->findOneBy(["user"=>$data,"niveau01"=>$niveau01]);
if($usermodo) {
$em->getManager()->remove($usermodo);
$em->getManager()->flush();
}
}
// Retour à la liste
if($access=="user")
return $this->redirectToRoute("app_home");
else
return $this->redirectToRoute(str_replace("_admin_","_".$access."_",$this->route));
}
// Affichage du formulaire
return $this->render($this->twig.'edit.html.twig', [
"useheader"=>true,
"usemenu"=>false,
"usesidebar"=>($access=="admin"),
"access"=>$access,
"mode"=>"update",
"form"=>$form->createView(),
$this->data=>$data,
"listgroups"=>$this->getListGroups($access,$em),
"listmodos"=> $this->getListModos($em),
"maxsize"=>($access=="user"?1200:null),
]);
}
public function delete($access,$id,Request $request,ManagerRegistry $em): Response
{
// Récupération de l'enregistrement courant
$data=$em->getRepository($this->entity)->find($id);
if (!$data) throw $this->createNotFoundException('Unable to find entity.');
// Controler les permissions
$this->candelete($access,$data,$em);
// Tentative de suppression
try{
$em->getManager()->remove($data);
$em->getManager()->flush();
}
catch (\Exception $e) {
$request->getSession()->getFlashBag()->add("error", $e->getMessage());
return $this->redirectToRoute(str_replace("_admin_","_".$access."_",$this->route)."_update",["id"=>$id]);
}
return $this->redirectToRoute(str_replace("_admin_","_".$access."_",$this->route));
}
protected function getListGroups($access,$em)
{
$qb=$em->getManager()->createQueryBuilder();
$qb->select('b')->from('App:Group','b');
if($access!="admin") $qb->where("b.isopen=true AND b.isworkgroup=true");
$qb->andWhere("b.ldapfilter IS NULL");
$qb->andWhere("b.attributes IS NULL");
$qb->andWhere("b.id>0");
$datas=$qb->getQuery()->getResult();
return $datas;
}
protected function getListModos($em)
{
$qb=$em->getManager()->createQueryBuilder();
$qb->select('b')->from('App:Niveau01','b');
$datas=$qb->getQuery()->getResult();
return $datas;
}
private function cansubmit($access,$em) {
switch($access) {
case "admin" : return true; break;
case "modo" : return true; break;
}
throw $this->createAccessDeniedException('Permission denied');
}
private function canupdate($access,$entity,$em) {
switch($access) {
case "admin" : return true; break;
case "modo" :
$usermodo=$em->getRepository("App\Entity\UserModo")->findOneBy(["user"=>$this->getUser(),"niveau01"=>$entity->getNiveau01()]);
if(!$usermodo) throw $this->createAccessDeniedException('Permission denied');
return true;
break;
case "user" :
if($this->getUser()->getId()!=$entity->getId()) throw $this->createAccessDeniedException('Permission denied');
return true;
break;
}
throw $this->createAccessDeniedException('Permission denied');
}
private function candelete($access,$entity,$em) {
switch($access) {
case "admin" : return true; break;
case "modo" :
$usermodo=$em->getRepository("App\Entity\UserModo")->findOneBy(["user"=>$this->getUser(),"niveau01"=>$entity->getNiveau01()]);
if(!$usermodo) throw $this->createAccessDeniedException('Permission denied');
if($entity->hasRole("ROLE_ADMIN")||$entity->hasRole("ROLE_MODO")) throw $this->createAccessDeniedException('Permission denied');
return true;
break;
case "user" :
if($this->getUser()->getId()!=$entity->getId()) throw $this->createAccessDeniedException('Permission denied');
return true;
break;
}
throw $this->createAccessDeniedException('Permission denied');
}
public function preference($access,Request $request,ManagerRegistry $em): Response
{
$key=$request->request->get('key');
$id=$request->request->get('id');
$value=$request->request->get('value');
// Récupérer les préférences de l'utilisateur
$preference=$this->getUser()->getPreference();
// Mise à jour de la préférence
$toupdate=false;
if(!is_array($preference)) {
$toupdate=true;
$preference=[];
}
if(!array_key_exists($key,$preference)) {
$toupdate=true;
$preference[$key]=[];
}
if((!array_key_exists($id,$preference[$key]))) {
$toupdate=true;
$preference[$key][$id]=$value;
}
if($preference[$key][$id]!=$value) {
$toupdate=true;
$preference[$key][$id]=$value;
}
// Mise à jour des préferences
if($toupdate) {
$this->getUser()->setPreference($preference);
$em->getManager()->flush();
}
return new Response();
}
}

View File

@ -0,0 +1,199 @@
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Doctrine\Persistence\ManagerRegistry;
use App\Entity\Whitelist as Entity;
use App\Form\WhitelistType as Form;
class WhitelistController extends AbstractController
{
private $data="whitelist";
private $entity="App\Entity\Whitelist";
private $twig="Whitelist/";
private $route="app_admin_whitelist";
public function list(): Response
{
return $this->render($this->twig.'list.html.twig',[
"useheader"=>true,
"usemenu"=>false,
"usesidebar"=>true,
]);
}
public function tablelist(Request $request,ManagerRegistry $em): Response
{
$query=$request->query->all();
$start=$query['start'];
$length=$query['length'];
$search=$query['search'];
$draw= $query['draw'];
$ordercolumn=$query['order'][0]['column'];
$orderdir=$query['order'][0]['dir'];
// Nombre total d'enregistrement
$total = $em->getManager()->createQueryBuilder()->select('COUNT(entity)')->from($this->entity,'entity')->getQuery()->getSingleScalarResult();
// Nombre d'enregistrement filtré
if(!$search||$search["value"]=="")
$totalf = $total;
else {
$totalf= $em->getManager()->createQueryBuilder()
->select('COUNT(entity)')
->from($this->entity,'entity')
->where('entity.label LIKE :value')
->setParameter("value", "%".$search["value"]."%")
->getQuery()
->getSingleScalarResult();
}
// Construction du tableau de retour
$output = array(
'draw' => $draw,
'recordsFiltered' => $totalf,
'recordsTotal' => $total,
'data' => array(),
);
// Parcours des Enregistrement
$qb = $em->getManager()->createQueryBuilder();
$qb->select('entity')->from($this->entity,'entity');
if($search&&$search["value"]!="") {
$qb ->andWhere('entity.label LIKE :value')
->setParameter("value", "%".$search["value"]."%");
}
if($ordercolumn) {
switch($ordercolumn) {
case 1 :
$qb->orderBy('entity.label',$orderdir);
break;
}
}
$datas=$qb->setFirstResult($start)->setMaxResults($length)->getQuery()->getResult();
foreach($datas as $data) {
// Action
$action = "";
$action.="<a href='".$this->generateUrl($this->route.'_update', array('id'=>$data->getId()))."'><i class='fa fa-file fa-fw fa-2x'></i></a>";
$tmp=array();
array_push($tmp,$action);
array_push($tmp,$data->getLabel());
if($this->getParameter("appMasteridentity")=="LDAP"||$this->getParameter("appSynchro")=="LDAP2NINE") array_push($tmp,$data->getLdapfilter());
if($this->getParameter("appMasteridentity")=="SSO") array_push($tmp,$data->getAttributes());
array_push($output["data"],$tmp);
}
// Retour
return new JsonResponse($output);
}
public function submit(Request $request,ManagerRegistry $em): Response
{
// Initialisation de l'enregistrement
$data = new Entity();
// Création du formulaire
$form = $this->createForm(Form::class,$data,array("mode"=>"submit"));
// Récupération des data du formulaire
$form->handleRequest($request);
// Sur validation
if ($form->get('submit')->isClicked() && $form->isValid()) {
$data = $form->getData();
// Sauvegarde
$em->getManager()->persist($data);
$em->getManager()->flush();
// Retour à la liste
return $this->redirectToRoute($this->route);
}
// Affichage du formulaire
return $this->render($this->twig.'edit.html.twig', [
"useheader"=>true,
"usemenu"=>false,
"usesidebar"=>true,
"mode"=>"submit",
"form"=>$form->createView(),
$this->data=>$data,
]);
}
public function update($id,Request $request,ManagerRegistry $em): Response
{
// Initialisation de l'enregistrement
$data=$em->getRepository($this->entity)->find($id);
if (!$data) throw $this->createNotFoundException('Unable to find entity.');
// Création du formulaire
$form = $this->createForm(Form::class,$data,array("mode"=>"update"));
// Récupération des data du formulaire
$form->handleRequest($request);
// Sur validation
if ($form->get('submit')->isClicked() && $form->isValid()) {
$data = $form->getData();
$em->getManager()->flush();
// Retour à la liste
return $this->redirectToRoute($this->route);
}
// Affichage du formulaire
return $this->render($this->twig.'edit.html.twig', [
'useheader' => true,
'usemenu' => false,
'usesidebar' => true,
$this->data => $data,
'mode' => 'update',
'form' => $form->createView()
]);
}
public function delete($id,Request $request,ManagerRegistry $em): Response
{
// Récupération de l'enregistrement courant
$data=$em->getRepository($this->entity)->find($id);
if (!$data) throw $this->createNotFoundException('Unable to find entity.');
// Tentative de suppression
try{
$em->getManager()->remove($data);
$em->getManager()->flush();
}
catch (\Exception $e) {
$request->getSession()->getFlashBag()->add("error", $e->getMessage());
return $this->redirectToRoute($this->route."_update",["id"=>$id]);
}
return $this->redirectToRoute($this->route);
}
public function is(Request $request,ManagerRegistry $em)
{
$email=$request->request->get('email');
$email=explode("@",$email);
$domaine=end($email);
// Rechercher le mail dans la liste blanche
$whitelist=$em->getRepository($this->entity)->findOneBy(["label"=>$domaine]);
if($whitelist)
return new Response("OK", 200);
else
return new Response("KO", 200);
}
}

0
src/Entity/.gitignore vendored Normal file
View File

227
src/Entity/Config.php Normal file
View File

@ -0,0 +1,227 @@
<?php
namespace App\Entity;
use App\Repository\ConfigRepository;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
/**
* Cron
*
* @ORM\Table(name="config")
* @ORM\HasLifecycleCallbacks()
* @ORM\Entity(repositoryClass="App\Repository\ConfigRepository")
*/
class Config
{ /**
* @ORM\Id
* @ORM\Column(type="string")
*/
private $id;
/**
* @ORM\Column(type="string", length=250)
*/
private $title;
/**
* @ORM\Column(type="text", nullable=true)
*/
private $value;
/**
* @ORM\Column(name="defaultvalue", type="text")
*/
private $default;
/**
* @ORM\Column(name="roworder", type="string")
*/
private $order;
/**
* @ORM\Column(type="boolean")
*/
private $visible;
/**
* @ORM\Column(type="boolean")
*/
private $changeable;
/**
* @ORM\Column(type="boolean")
*/
private $required;
/**
* @ORM\Column(type="string")
*/
private $type;
/**
* @ORM\Column(type="string")
*/
private $grouped;
/**
* @ORM\Column(type="string")
*/
private $category;
/**
* @ORM\Column(type="text")
*/
private $help;
//== CODE A NE PAS REGENERER
public function setId(string $id): self
{
$this->id = $id;
return $this;
}
public function getValue(): ?string
{
if($this->value=="") return $this->default;
else return $this->value;
}
//== FIN DU CODE A NE PAS REGENERER
public function getId(): ?string
{
return $this->id;
}
public function getTitle(): ?string
{
return $this->title;
}
public function setTitle(string $title): self
{
$this->title = $title;
return $this;
}
public function setValue(?string $value): self
{
$this->value = $value;
return $this;
}
public function getDefault(): ?string
{
return $this->default;
}
public function setDefault(string $default): self
{
$this->default = $default;
return $this;
}
public function getOrder(): ?string
{
return $this->order;
}
public function setOrder(string $order): self
{
$this->order = $order;
return $this;
}
public function isVisible(): ?bool
{
return $this->visible;
}
public function setVisible(bool $visible): self
{
$this->visible = $visible;
return $this;
}
public function isChangeable(): ?bool
{
return $this->changeable;
}
public function setChangeable(bool $changeable): self
{
$this->changeable = $changeable;
return $this;
}
public function isRequired(): ?bool
{
return $this->required;
}
public function setRequired(bool $required): self
{
$this->required = $required;
return $this;
}
public function getType(): ?string
{
return $this->type;
}
public function setType(string $type): self
{
$this->type = $type;
return $this;
}
public function getGrouped(): ?string
{
return $this->grouped;
}
public function setGrouped(string $grouped): self
{
$this->grouped = $grouped;
return $this;
}
public function getCategory(): ?string
{
return $this->category;
}
public function setCategory(string $category): self
{
$this->category = $category;
return $this;
}
public function getHelp(): ?string
{
return $this->help;
}
public function setHelp(string $help): self
{
$this->help = $help;
return $this;
}
}

210
src/Entity/Cron.php Normal file
View File

@ -0,0 +1,210 @@
<?php
namespace App\Entity;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Cron
*
* @ORM\Table(name="cron")
* @ORM\Entity(repositoryClass="App\Repository\CronRepository")
*/
class Cron
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="command", type="string", nullable=false)
* @Assert\NotBlank()
*
*/
private $command;
/**
* @ORM\Column(type="text", nullable=true)
*/
private $description;
/**
* @ORM\Column(type="integer", nullable=true)
*/
private $statut;
/**
* @ORM\Column(type="datetime", nullable=false)
*/
private $submitdate;
/**
* @ORM\Column(type="datetime", nullable=true)
*/
private $startexecdate;
/**
* @ORM\Column(type="datetime", nullable=true)
*/
private $endexecdate;
/**
* @ORM\Column(type="datetime", nullable=true)
*/
private $nextexecdate;
/**
* @ORM\Column(type="integer", nullable=true)
*/
private $repeatinterval;
/**
* @ORM\Column(type="text", nullable=true)
*/
private $jsonargument;
// A garder pour forcer l'id en init
public function setId($id)
{
$this->id = $id;
return $this;
}
public function __construct()
{
$this->submitdate = new \DateTime();
}
// A garder pour récupérer le label du statut
public function getStatutLabel()
{
switch($this->statut) {
case -1: return "Désactivé"; break;
case 0: return "KO"; break;
case 1: return "OK"; break;
}
}
public function getId(): ?int
{
return $this->id;
}
public function getCommand(): ?string
{
return $this->command;
}
public function setCommand(string $command): self
{
$this->command = $command;
return $this;
}
public function getDescription(): ?string
{
return $this->description;
}
public function setDescription(?string $description): self
{
$this->description = $description;
return $this;
}
public function getStatut(): ?int
{
return $this->statut;
}
public function setStatut($statut): self
{
$this->statut = $statut;
return $this;
}
public function getSubmitdate(): ?\DateTimeInterface
{
return $this->submitdate;
}
public function setSubmitdate(\DateTimeInterface $submitdate): self
{
$this->submitdate = $submitdate;
return $this;
}
public function getStartexecdate(): ?\DateTimeInterface
{
return $this->startexecdate;
}
public function setStartexecdate(?\DateTimeInterface $startexecdate): self
{
$this->startexecdate = $startexecdate;
return $this;
}
public function getEndexecdate(): ?\DateTimeInterface
{
return $this->endexecdate;
}
public function setEndexecdate(?\DateTimeInterface $endexecdate): self
{
$this->endexecdate = $endexecdate;
return $this;
}
public function getNextexecdate(): ?\DateTimeInterface
{
return $this->nextexecdate;
}
public function setNextexecdate(?\DateTimeInterface $nextexecdate): self
{
$this->nextexecdate = $nextexecdate;
return $this;
}
public function getRepeatinterval(): ?int
{
return $this->repeatinterval;
}
public function setRepeatinterval(?int $repeatinterval): self
{
$this->repeatinterval = $repeatinterval;
return $this;
}
public function getJsonargument(): ?string
{
return $this->jsonargument;
}
public function setJsonargument(?string $jsonargument): self
{
$this->jsonargument = $jsonargument;
return $this;
}
}

268
src/Entity/Group.php Normal file
View File

@ -0,0 +1,268 @@
<?php
namespace App\Entity;
use Doctrine\Common\Collections\Collection;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* @ORM\Entity
* @ORM\Table(name="groupe")
* @ORM\HasLifecycleCallbacks()
* @ORM\Entity(repositoryClass="App\Repository\GroupRepository")
*
* @UniqueEntity(fields="label", message="Un group existe déjà avec ce label")
*/
class Group
{
/**
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\Column(type="string", length=250, unique=true)
*/
private $label;
/**
* @var string
*
* @ORM\Column(name="description", type="text", nullable=true)
*/
private $description;
/**
* @ORM\Column(type="string", length=250, nullable=true)
*/
private $email;
/**
* @ORM\Column(type="boolean", options={"default" : false})
*/
private $isopen;
/**
* @ORM\Column(type="boolean", options={"default" : false})
*/
private $isworkgroup;
/**
* @ORM\Column(type="string")
*/
private $apikey;
/**
* @ORM\Column(type="text", nullable=true)
*/
private $ldapfilter;
/**
* @ORM\Column(type="text", nullable=true)
*/
private $attributes;
/**
* @ORM\Column(type="text", nullable=true)
*/
private $idexternal;
/**
* @ORM\ManyToOne(targetEntity="User", inversedBy="ownergroups")
* @ORM\JoinColumn(nullable=true, onDelete="SET NULL")
*/
private $owner;
/**
* @var ArrayCollection $users
* @var UserGroup
*
* @ORM\OneToMany(targetEntity="UserGroup", mappedBy="group", cascade={"persist"}, orphanRemoval=true)
*/
private $users;
public function __construct()
{
$this->users = new ArrayCollection();
}
//== CODE A NE PAS REGENERER
public function setId(int $id): self
{
$this->id = $id;
return $this;
}
//== FIN DU CODE A NE PAS REGENERER
public function getId(): ?int
{
return $this->id;
}
public function getLabel(): ?string
{
return $this->label;
}
public function setLabel(string $label): self
{
$this->label = $label;
return $this;
}
public function getDescription(): ?string
{
return $this->description;
}
public function setDescription(?string $description): self
{
$this->description = $description;
return $this;
}
public function getEmail(): ?string
{
return $this->email;
}
public function setEmail(?string $email): self
{
$this->email = $email;
return $this;
}
public function isIsopen(): ?bool
{
return $this->isopen;
}
public function setIsopen(bool $isopen): self
{
$this->isopen = $isopen;
return $this;
}
public function isIsworkgroup(): ?bool
{
return $this->isworkgroup;
}
public function setIsworkgroup(bool $isworkgroup): self
{
$this->isworkgroup = $isworkgroup;
return $this;
}
public function getApikey(): ?string
{
return $this->apikey;
}
public function setApikey(string $apikey): self
{
$this->apikey = $apikey;
return $this;
}
public function getLdapfilter(): ?string
{
return $this->ldapfilter;
}
public function setLdapfilter(?string $ldapfilter): self
{
$this->ldapfilter = $ldapfilter;
return $this;
}
public function getAttributes(): ?string
{
return $this->attributes;
}
public function setAttributes(?string $attributes): self
{
$this->attributes = $attributes;
return $this;
}
public function getIdexternal(): ?string
{
return $this->idexternal;
}
public function setIdexternal(?string $idexternal): self
{
$this->idexternal = $idexternal;
return $this;
}
public function getInvitations(): ?array
{
return $this->invitations;
}
public function setInvitations(?array $invitations): self
{
$this->invitations = $invitations;
return $this;
}
public function getOwner(): ?User
{
return $this->owner;
}
public function setOwner(?User $owner): self
{
$this->owner = $owner;
return $this;
}
/**
* @return Collection<int, UserGroup>
*/
public function getUsers(): Collection
{
return $this->users;
}
public function addUser(UserGroup $user): self
{
if (!$this->users->contains($user)) {
$this->users[] = $user;
$user->setGroup($this);
}
return $this;
}
public function removeUser(UserGroup $user): self
{
if ($this->users->removeElement($user)) {
// set the owning side to null (unless already changed)
if ($user->getGroup() === $this) {
$user->setGroup(null);
}
}
return $this;
}
}

292
src/Entity/Niveau01.php Normal file
View File

@ -0,0 +1,292 @@
<?php
namespace App\Entity;
use Doctrine\Common\Collections\Collection;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use App\Validator as Validator;
/**
* @ORM\Entity
* @ORM\Table(name="niveau01")
* @ORM\HasLifecycleCallbacks()
* @ORM\Entity(repositoryClass="App\Repository\Niveau01Repository")
*
* @UniqueEntity(fields="label", message="Un Niveau de rang 01 existe déjà avec ce label")
*/
class Niveau01
{
/**
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\Column(type="string", length=250, unique=true)
* @Validator\Grouplabel()
* @Validator\Niveau01unique()
*/
private $label;
/**
* @ORM\Column(type="string")
*/
private $apikey;
/**
* @ORM\Column(type="text", nullable=true)
*/
private $ldapfilter;
/**
* @ORM\Column(type="text", nullable=true)
*/
private $attributes;
/**
* @ORM\Column(type="text", nullable=true)
*/
private $idexternal;
/**
* @var ArrayCollection $niveau02s
* @var Registration
*
* @ORM\OneToMany(targetEntity="Niveau02", mappedBy="niveau01", cascade={"persist"}, orphanRemoval=false)
*/
private $niveau02s;
/**
* @var ArrayCollection $registrations
* @var Registration
*
* @ORM\OneToMany(targetEntity="Registration", mappedBy="niveau01", cascade={"persist"}, orphanRemoval=false)
*/
private $registrations;
/**
* @var ArrayCollection $users
* @var User
*
* @ORM\OneToMany(targetEntity="User", mappedBy="niveau01", cascade={"persist"}, orphanRemoval=false)
*/
private $users;
/**
* @var ArrayCollection $modos
* @var User
*
* @ORM\OneToMany(targetEntity="UserModo", mappedBy="niveau01", cascade={"persist"}, orphanRemoval=false)
*/
private $modos;
public function __construct()
{
$this->niveau02s = new ArrayCollection();
$this->registrations = new ArrayCollection();
$this->users = new ArrayCollection();
$this->modos = new ArrayCollection();
}
//== CODE A NE PAS REGENERER
public function setId(int $id): self
{
$this->id = $id;
return $this;
}
//== FIN DU CODE A NE PAS REGENERER
public function getId(): ?int
{
return $this->id;
}
public function getLabel(): ?string
{
return $this->label;
}
public function setLabel(string $label): self
{
$this->label = $label;
return $this;
}
public function getApikey(): ?string
{
return $this->apikey;
}
public function setApikey(string $apikey): self
{
$this->apikey = $apikey;
return $this;
}
public function getLdapfilter(): ?string
{
return $this->ldapfilter;
}
public function setLdapfilter(?string $ldapfilter): self
{
$this->ldapfilter = $ldapfilter;
return $this;
}
public function getAttributes(): ?string
{
return $this->attributes;
}
public function setAttributes(?string $attributes): self
{
$this->attributes = $attributes;
return $this;
}
public function getIdexternal(): ?string
{
return $this->idexternal;
}
public function setIdexternal(?string $idexternal): self
{
$this->idexternal = $idexternal;
return $this;
}
/**
* @return Collection<int, Niveau02>
*/
public function getNiveau02s(): Collection
{
return $this->niveau02s;
}
public function addNiveau02(Niveau02 $niveau02): self
{
if (!$this->niveau02s->contains($niveau02)) {
$this->niveau02s[] = $niveau02;
$niveau02->setNiveau01($this);
}
return $this;
}
public function removeNiveau02(Niveau02 $niveau02): self
{
if ($this->niveau02s->removeElement($niveau02)) {
// set the owning side to null (unless already changed)
if ($niveau02->getNiveau01() === $this) {
$niveau02->setNiveau01(null);
}
}
return $this;
}
/**
* @return Collection<int, Registration>
*/
public function getRegistrations(): Collection
{
return $this->registrations;
}
public function addRegistration(Registration $registration): self
{
if (!$this->registrations->contains($registration)) {
$this->registrations[] = $registration;
$registration->setNiveau01($this);
}
return $this;
}
public function removeRegistration(Registration $registration): self
{
if ($this->registrations->removeElement($registration)) {
// set the owning side to null (unless already changed)
if ($registration->getNiveau01() === $this) {
$registration->setNiveau01(null);
}
}
return $this;
}
/**
* @return Collection<int, User>
*/
public function getUsers(): Collection
{
return $this->users;
}
public function addUser(User $user): self
{
if (!$this->users->contains($user)) {
$this->users[] = $user;
$user->setNiveau01($this);
}
return $this;
}
public function removeUser(User $user): self
{
if ($this->users->removeElement($user)) {
// set the owning side to null (unless already changed)
if ($user->getNiveau01() === $this) {
$user->setNiveau01(null);
}
}
return $this;
}
/**
* @return Collection<int, UserModo>
*/
public function getModos(): Collection
{
return $this->modos;
}
public function addModo(UserModo $modo): self
{
if (!$this->modos->contains($modo)) {
$this->modos[] = $modo;
$modo->setNiveau01($this);
}
return $this;
}
public function removeModo(UserModo $modo): self
{
if ($this->modos->removeElement($modo)) {
// set the owning side to null (unless already changed)
if ($modo->getNiveau01() === $this) {
$modo->setNiveau01(null);
}
}
return $this;
}
}

169
src/Entity/Niveau02.php Normal file
View File

@ -0,0 +1,169 @@
<?php
namespace App\Entity;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use App\Validator as Validator;
/**
* @ORM\Entity
* @ORM\Table(name="niveau02")
* @ORM\HasLifecycleCallbacks()
* @ORM\Entity(repositoryClass="App\Repository\Niveau02Repository")
*
* @UniqueEntity(fields="label", message="Un Niveau de rang 2 existe déjà avec ce label")
*/
class Niveau02
{
/**
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\Column(type="string", length=250, unique=true)
* @Validator\Grouplabel()
* @Validator\Niveau02unique()
*/
private $label;
/**
* @ORM\Column(type="string")
*/
private $apikey;
/**
* @ORM\ManyToOne(targetEntity="Niveau01", inversedBy="niveau02s")
* @ORM\JoinColumn(nullable=false)
*/
private $niveau01;
/**
* @var ArrayCollection $registrations
* @var Registration
*
* @ORM\OneToMany(targetEntity="Registration", mappedBy="niveau02", cascade={"persist"}, orphanRemoval=false)
*/
private $registrations;
/**
* @var ArrayCollection $users
* @var User
*
* @ORM\OneToMany(targetEntity="User", mappedBy="niveau02", cascade={"persist"}, orphanRemoval=false)
*/
private $users;
public function __construct()
{
$this->registrations = new ArrayCollection();
$this->users = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getLabel(): ?string
{
return $this->label;
}
public function setLabel(string $label): self
{
$this->label = $label;
return $this;
}
public function getApikey(): ?string
{
return $this->apikey;
}
public function setApikey(string $apikey): self
{
$this->apikey = $apikey;
return $this;
}
public function getNiveau01(): ?Niveau01
{
return $this->niveau01;
}
public function setNiveau01(?Niveau01 $niveau01): self
{
$this->niveau01 = $niveau01;
return $this;
}
/**
* @return Collection<int, Registration>
*/
public function getRegistrations(): Collection
{
return $this->registrations;
}
public function addRegistration(Registration $registration): self
{
if (!$this->registrations->contains($registration)) {
$this->registrations[] = $registration;
$registration->setNiveau02($this);
}
return $this;
}
public function removeRegistration(Registration $registration): self
{
if ($this->registrations->removeElement($registration)) {
// set the owning side to null (unless already changed)
if ($registration->getNiveau02() === $this) {
$registration->setNiveau02(null);
}
}
return $this;
}
/**
* @return Collection<int, User>
*/
public function getUsers(): Collection
{
return $this->users;
}
public function addUser(User $user): self
{
if (!$this->users->contains($user)) {
$this->users[] = $user;
$user->setNiveau02($this);
}
return $this;
}
public function removeUser(User $user): self
{
if ($this->users->removeElement($user)) {
// set the owning side to null (unless already changed)
if ($user->getNiveau02() === $this) {
$user->setNiveau02(null);
}
}
return $this;
}
}

416
src/Entity/Registration.php Normal file
View File

@ -0,0 +1,416 @@
<?php
namespace App\Entity;
use Doctrine\Common\Collections\Collection;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\LegacyPasswordAuthenticatedUserInterface;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use App\Validator as Validator;
/**
* @ORM\Entity
* @ORM\HasLifecycleCallbacks()
* @ORM\Entity(repositoryClass="App\Repository\RegistrationRepository")
*
* @UniqueEntity(fields="username", message="Un utilisateur existe déjà avec ce login.")
* @UniqueEntity(fields="email", message="Un utilisateur existe déjà avec ce mail.")
*/
class Registration implements UserInterface, LegacyPasswordAuthenticatedUserInterface
{
/**
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\Column(type="string", length=128, unique=true)
* @Validator\Userusername()
*/
private $username;
/**
* @ORM\Column(type="string", length=250, nullable=true)
*/
private $firstname;
/**
* @ORM\Column(type="string", length=250, nullable=true)
*/
private $lastname;
/**
* @ORM\Column(type="string", length=250)
*/
private $password;
/**
* @Validator\Password()
*/
private $passwordplain;
/**
* @ORM\Column(type="string", length=250)
*/
private $salt;
/**
* @ORM\Column(type="string", length=128, unique=true)
*/
private $email;
/**
* @ORM\Column(type="boolean")
*/
protected $isvisible;
/**
* @ORM\Column(type="string", length=250, nullable=true)
*/
private $postaladress;
/**
* @ORM\Column(type="string", length=60, nullable=true)
*/
private $telephonenumber;
/**
* @ORM\Column(type="string", length=250, nullable=true)
*/
private $job;
/**
* @ORM\Column(type="string", length=250, nullable=true)
*/
private $position;
/**
* @ORM\Column(name="motivation", type="text", nullable=true)
*/
private $motivation;
/**
* @ORM\Column(name="note", type="text", nullable=true)
*/
private $note;
/**
* @ORM\Column(type="datetime", nullable=true)
*/
private $keyexpire;
/**
* @ORM\Column(type="string", length=60, nullable=true)
*/
private $keyvalue;
/**
* @ORM\Column(type="integer", length=60, nullable=false)
*/
private $statut;
/**
* @ORM\ManyToOne(targetEntity="Niveau01", inversedBy="registrations")
* @ORM\JoinColumn(nullable=false)
*/
private $niveau01;
/**
* @ORM\ManyToOne(targetEntity="Niveau02", inversedBy="registrations")
*/
private $niveau02;
//== CODE A NE PAS REGENERER
public function getUserIdentifier(): string
{
return $this->username;
}
public function setPasswordDirect($password)
{
// Permet de setter le password généré lors de l'inscription
$this->password = $password;
return $this;
}
/**
* @see PasswordAuthenticatedUserInterface
*/
public function getPassword(): string
{
return $this->password;
}
public function setPassword($password): self
{
if($password!=$this->password&&$password!=""){
// Placer le password non encodé dans une variable tempo sur laquel on va appliquer la contraite de form
$this->passwordplain = $password;
// Password encrypté format openldap
$this->salt = uniqid(mt_rand(), true);
$hash = "{SSHA}" . base64_encode(pack("H*", sha1($password . $this->salt)) . $this->salt);
$this->password = $hash;
}
return $this;
}
/**
* Returning a salt is only needed, if you are not using a modern
* hashing algorithm (e.g. bcrypt or sodium) in your security.yaml.
*
* @see UserInterface
*/
public function getSalt(): ?string
{
return $this->salt;
}
/**
* @see UserInterface
*/
public function eraseCredentials()
{
$this->passwordplain = null;
}
public function getRoles(): array
{
return $this->roles;
}
public function hasRole(string $role): ?bool
{
return in_array($role,$this->getRoles());
}
public function setRole(string $role): self
{
if(!$this->hasRole($role))
array_push($this->roles,$role);
return $this;
}
public function getDisplayname() {
return $this->firstname." ".$this->lastname;
}
//== FIN DU CODE A NE PAS REGENERER
public function getId(): ?int
{
return $this->id;
}
public function getUsername(): ?string
{
return $this->username;
}
public function setUsername(string $username): self
{
$this->username = $username;
return $this;
}
public function getFirstname(): ?string
{
return $this->firstname;
}
public function setFirstname(?string $firstname): self
{
$this->firstname = $firstname;
return $this;
}
public function getLastname(): ?string
{
return $this->lastname;
}
public function setLastname(?string $lastname): self
{
$this->lastname = $lastname;
return $this;
}
public function setSalt(string $salt): self
{
$this->salt = $salt;
return $this;
}
public function getEmail(): ?string
{
return $this->email;
}
public function setEmail(string $email): self
{
$this->email = $email;
return $this;
}
public function isIsvisible(): ?bool
{
return $this->isvisible;
}
public function setIsvisible(bool $isvisible): self
{
$this->isvisible = $isvisible;
return $this;
}
public function getPostaladress(): ?string
{
return $this->postaladress;
}
public function setPostaladress(?string $postaladress): self
{
$this->postaladress = $postaladress;
return $this;
}
public function getTelephonenumber(): ?string
{
return $this->telephonenumber;
}
public function setTelephonenumber(?string $telephonenumber): self
{
$this->telephonenumber = $telephonenumber;
return $this;
}
public function getJob(): ?string
{
return $this->job;
}
public function setJob(?string $job): self
{
$this->job = $job;
return $this;
}
public function getPosition(): ?string
{
return $this->position;
}
public function setPosition(?string $position): self
{
$this->position = $position;
return $this;
}
public function getMotivation(): ?string
{
return $this->motivation;
}
public function setMotivation(?string $motivation): self
{
$this->motivation = $motivation;
return $this;
}
public function getNote(): ?string
{
return $this->note;
}
public function setNote(?string $note): self
{
$this->note = $note;
return $this;
}
public function getKeyexpire(): ?\DateTimeInterface
{
return $this->keyexpire;
}
public function setKeyexpire(?\DateTimeInterface $keyexpire): self
{
$this->keyexpire = $keyexpire;
return $this;
}
public function getKeyvalue(): ?string
{
return $this->keyvalue;
}
public function setKeyvalue(?string $keyvalue): self
{
$this->keyvalue = $keyvalue;
return $this;
}
public function getStatut(): ?int
{
return $this->statut;
}
public function setStatut(int $statut): self
{
$this->statut = $statut;
return $this;
}
public function getNiveau01(): ?Niveau01
{
return $this->niveau01;
}
public function setNiveau01(?Niveau01 $niveau01): self
{
$this->niveau01 = $niveau01;
return $this;
}
public function getNiveau02(): ?Niveau02
{
return $this->niveau02;
}
public function setNiveau02(?Niveau02 $niveau02): self
{
$this->niveau02 = $niveau02;
return $this;
}
}

626
src/Entity/User.php Normal file
View File

@ -0,0 +1,626 @@
<?php
namespace App\Entity;
use Doctrine\Common\Collections\Collection;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\LegacyPasswordAuthenticatedUserInterface;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use App\Validator as Validator;
/**
* @ORM\Entity
* @ORM\Table(name="useraccount")
* @ORM\HasLifecycleCallbacks()
* @ORM\Entity(repositoryClass="App\Repository\UserRepository")
*
* @UniqueEntity(fields="username", message="Un utilisateur existe déjà avec ce login.")
* @UniqueEntity(fields="email", message="Un utilisateur existe déjà avec ce mail.")
*/
class User implements UserInterface, LegacyPasswordAuthenticatedUserInterface
{
/**
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\Column(type="string", length=128, unique=true)
* @Validator\Userusername()
*/
private $username;
/**
* @ORM\Column(type="string")
*/
private $apikey;
/**
* @ORM\Column(type="string", length=250, nullable=true)
*/
private $firstname;
/**
* @ORM\Column(type="string", length=250, nullable=true)
*/
private $lastname;
/**
* @var array
*
* @ORM\Column(type="array", length=255)
*/
private $roles = array();
/**
* @ORM\Column(type="string", length=250)
*/
private $password;
/**
* @Validator\Password()
*/
private $passwordplain;
/**
* @ORM\Column(type="string", length=250)
*/
private $salt;
/**
* @ORM\Column(type="string", length=128, unique=true)
*/
private $email;
/**
* @ORM\Column(type="string", length=250, nullable=true, options={"default" : 0})
*/
private $avatar;
/**
* @ORM\Column(type="boolean")
*/
protected $isvisible;
/**
* @ORM\Column(type="text", nullable=true)
*/
private $postaladress;
/**
* @ORM\Column(type="string", length=60, nullable=true)
*/
private $telephonenumber;
/**
* @ORM\Column(type="string", length=250, nullable=true)
*/
private $job;
/**
* @ORM\Column(type="string", length=250, nullable=true)
*/
private $position;
/**
* @ORM\Column(type="text", nullable=true)
*/
private $motivation;
/**
* @ORM\Column(type="text", nullable=true)
*/
private $note;
/**
* @ORM\Column(type="array", nullable=true)
*/
private $preference;
/**
* @ORM\Column(type="datetime", nullable=true)
*/
private $keyexpire;
/**
* @ORM\Column(type="string", length=60, nullable=true)
*/
private $keyvalue;
/**
* @ORM\Column(type="datetime", nullable=true)
*/
private $visitedate;
/**
* @ORM\Column(type="integer", nullable=true)
*/
private $visitecpt;
/**
* @ORM\ManyToOne(targetEntity="Niveau01", inversedBy="users")
* @ORM\JoinColumn(nullable=false)
*/
private $niveau01;
/**
* @ORM\ManyToOne(targetEntity="Niveau02", inversedBy="users")
*/
private $niveau02;
/**
* @var ArrayCollection $groups
* @var UserGroup
*
* @ORM\OneToMany(targetEntity="UserGroup", mappedBy="user", cascade={"persist"}, orphanRemoval=true)
*/
private $groups;
/**
* @var ArrayCollection $ownergroups
* @var Group
*
* @ORM\OneToMany(targetEntity="Group", mappedBy="owner", cascade={"persist"}, orphanRemoval=false)
*/
private $ownergroups;
/**
* @var ArrayCollection $groups
* @var UserGroup
*
* @ORM\OneToMany(targetEntity="UserModo", mappedBy="user", cascade={"persist"}, orphanRemoval=true)
*/
private $modos;
public function __construct()
{
$this->groups = new ArrayCollection();
$this->ownergroups = new ArrayCollection();
$this->modos = new ArrayCollection();
}
//== CODE A NE PAS REGENERER
public function setId(int $id): self
{
$this->id = $id;
return $this;
}
public function getUserIdentifier(): string
{
return $this->username;
}
public function setPasswordDirect($password)
{
// Permet de setter le password généré lors de l'inscription
$this->password = $password;
return $this;
}
/**
* @see PasswordAuthenticatedUserInterface
*/
public function getPassword(): string
{
return $this->password;
}
public function setPassword($password): self
{
if($password!=$this->password&&$password!=""){
// Placer le password non encodé dans une variable tempo sur laquel on va appliquer la contraite de form
$this->passwordplain = $password;
// Password encrypté format openldap
$this->salt = uniqid(mt_rand(), true);
$hash = "{SSHA}" . base64_encode(pack("H*", sha1($password . $this->salt)) . $this->salt);
$this->password = $hash;
}
return $this;
}
/**
* Returning a salt is only needed, if you are not using a modern
* hashing algorithm (e.g. bcrypt or sodium) in your security.yaml.
*
* @see UserInterface
*/
public function getSalt(): ?string
{
return $this->salt;
}
/**
* @see UserInterface
*/
public function eraseCredentials()
{
$this->passwordplain = null;
}
public function getRoles(): array
{
return $this->roles;
}
public function hasRole(string $role): ?bool
{
return in_array($role,$this->getRoles());
}
public function setRole(string $role): self
{
if(!$this->hasRole($role))
array_push($this->roles,$role);
return $this;
}
public function getDisplayname() {
return $this->firstname." ".$this->lastname;
}
//== FIN DU CODE A NE PAS REGENERER
public function getId(): ?int
{
return $this->id;
}
public function getUsername(): ?string
{
return $this->username;
}
public function setUsername(string $username): self
{
$this->username = $username;
return $this;
}
public function getApikey(): ?string
{
return $this->apikey;
}
public function setApikey(string $apikey): self
{
$this->apikey = $apikey;
return $this;
}
public function getFirstname(): ?string
{
return $this->firstname;
}
public function setFirstname(?string $firstname): self
{
$this->firstname = $firstname;
return $this;
}
public function getLastname(): ?string
{
return $this->lastname;
}
public function setLastname(?string $lastname): self
{
$this->lastname = $lastname;
return $this;
}
public function setRoles(array $roles): self
{
$this->roles = $roles;
return $this;
}
public function setSalt(string $salt): self
{
$this->salt = $salt;
return $this;
}
public function getEmail(): ?string
{
return $this->email;
}
public function setEmail(string $email): self
{
$this->email = $email;
return $this;
}
public function getAvatar(): ?string
{
return $this->avatar;
}
public function setAvatar(?string $avatar): self
{
$this->avatar = $avatar;
return $this;
}
public function isIsvisible(): ?bool
{
return $this->isvisible;
}
public function setIsvisible(bool $isvisible): self
{
$this->isvisible = $isvisible;
return $this;
}
public function getPostaladress(): ?string
{
return $this->postaladress;
}
public function setPostaladress(?string $postaladress): self
{
$this->postaladress = $postaladress;
return $this;
}
public function getTelephonenumber(): ?string
{
return $this->telephonenumber;
}
public function setTelephonenumber(?string $telephonenumber): self
{
$this->telephonenumber = $telephonenumber;
return $this;
}
public function getJob(): ?string
{
return $this->job;
}
public function setJob(?string $job): self
{
$this->job = $job;
return $this;
}
public function getPosition(): ?string
{
return $this->position;
}
public function setPosition(?string $position): self
{
$this->position = $position;
return $this;
}
public function getMotivation(): ?string
{
return $this->motivation;
}
public function setMotivation(?string $motivation): self
{
$this->motivation = $motivation;
return $this;
}
public function getNote(): ?string
{
return $this->note;
}
public function setNote(?string $note): self
{
$this->note = $note;
return $this;
}
public function getPreference(): ?array
{
return $this->preference;
}
public function setPreference(?array $preference): self
{
$this->preference = $preference;
return $this;
}
public function getKeyexpire(): ?\DateTimeInterface
{
return $this->keyexpire;
}
public function setKeyexpire(?\DateTimeInterface $keyexpire): self
{
$this->keyexpire = $keyexpire;
return $this;
}
public function getKeyvalue(): ?string
{
return $this->keyvalue;
}
public function setKeyvalue(?string $keyvalue): self
{
$this->keyvalue = $keyvalue;
return $this;
}
public function getVisitedate(): ?\DateTimeInterface
{
return $this->visitedate;
}
public function setVisitedate(?\DateTimeInterface $visitedate): self
{
$this->visitedate = $visitedate;
return $this;
}
public function getVisitecpt(): ?int
{
return $this->visitecpt;
}
public function setVisitecpt(?int $visitecpt): self
{
$this->visitecpt = $visitecpt;
return $this;
}
public function getNiveau01(): ?Niveau01
{
return $this->niveau01;
}
public function setNiveau01(?Niveau01 $niveau01): self
{
$this->niveau01 = $niveau01;
return $this;
}
public function getNiveau02(): ?Niveau02
{
return $this->niveau02;
}
public function setNiveau02(?Niveau02 $niveau02): self
{
$this->niveau02 = $niveau02;
return $this;
}
/**
* @return Collection<int, UserGroup>
*/
public function getGroups(): Collection
{
return $this->groups;
}
public function addGroup(UserGroup $group): self
{
if (!$this->groups->contains($group)) {
$this->groups[] = $group;
$group->setUser($this);
}
return $this;
}
public function removeGroup(UserGroup $group): self
{
if ($this->groups->removeElement($group)) {
// set the owning side to null (unless already changed)
if ($group->getUser() === $this) {
$group->setUser(null);
}
}
return $this;
}
/**
* @return Collection<int, Group>
*/
public function getOwnergroups(): Collection
{
return $this->ownergroups;
}
public function addOwnergroup(Group $ownergroup): self
{
if (!$this->ownergroups->contains($ownergroup)) {
$this->ownergroups[] = $ownergroup;
$ownergroup->setOwner($this);
}
return $this;
}
public function removeOwnergroup(Group $ownergroup): self
{
if ($this->ownergroups->removeElement($ownergroup)) {
// set the owning side to null (unless already changed)
if ($ownergroup->getOwner() === $this) {
$ownergroup->setOwner(null);
}
}
return $this;
}
/**
* @return Collection<int, UserModo>
*/
public function getModos(): Collection
{
return $this->modos;
}
public function addModo(UserModo $modo): self
{
if (!$this->modos->contains($modo)) {
$this->modos[] = $modo;
$modo->setUser($this);
}
return $this;
}
public function removeModo(UserModo $modo): self
{
if ($this->modos->removeElement($modo)) {
// set the owning side to null (unless already changed)
if ($modo->getUser() === $this) {
$modo->setUser(null);
}
}
return $this;
}
}

132
src/Entity/UserGroup.php Normal file
View File

@ -0,0 +1,132 @@
<?php
namespace App\Entity;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* @ORM\Entity
* @ORM\Table(name="usergroupe",uniqueConstraints={@ORM\UniqueConstraint(columns={"user_id", "group_id"})})
* @ORM\HasLifecycleCallbacks()
* @ORM\Entity(repositoryClass="App\Repository\UserGroupRepository")
*
* @UniqueEntity(fields={"user", "group"}, message="Cette liaison existe déjà !")
*/
class UserGroup
{
/**
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\Column(type="integer", length=60)
*/
private $rolegroup;
/**
* @ORM\Column(type="string", length=60)
*/
private $apikey;
/**
* @ORM\Column(type="datetime", nullable=true)
*/
private $visitedate;
/**
* @ORM\Column(type="integer", nullable=true)
*/
private $visitecpt;
/**
* @ORM\ManyToOne(targetEntity="User", inversedBy="groups")
*/
private $user;
/**
* @ORM\ManyToOne(targetEntity="Group", inversedBy="users")
*/
private $group;
public function getId(): ?int
{
return $this->id;
}
public function getRolegroup(): ?int
{
return $this->rolegroup;
}
public function setRolegroup(int $rolegroup): self
{
$this->rolegroup = $rolegroup;
return $this;
}
public function getApikey(): ?string
{
return $this->apikey;
}
public function setApikey(string $apikey): self
{
$this->apikey = $apikey;
return $this;
}
public function getVisitedate(): ?\DateTimeInterface
{
return $this->visitedate;
}
public function setVisitedate(?\DateTimeInterface $visitedate): self
{
$this->visitedate = $visitedate;
return $this;
}
public function getVisitecpt(): ?int
{
return $this->visitecpt;
}
public function setVisitecpt(?int $visitecpt): self
{
$this->visitecpt = $visitecpt;
return $this;
}
public function getUser(): ?User
{
return $this->user;
}
public function setUser(?User $user): self
{
$this->user = $user;
return $this;
}
public function getGroup(): ?Group
{
return $this->group;
}
public function setGroup(?Group $group): self
{
$this->group = $group;
return $this;
}
}

62
src/Entity/UserModo.php Normal file
View File

@ -0,0 +1,62 @@
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* @ORM\Entity
* @ORM\Table(name="usermodo")
*
* @UniqueEntity(fields={"user", "niveau01"}, message="Cette liaison existe déjà !")
*/
class UserModo
{
/**
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\ManyToOne(targetEntity="User", inversedBy="modos")
* @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=false)
*/
private $user;
/**
* @ORM\ManyToOne(targetEntity="Niveau01", inversedBy="modos")
* @ORM\JoinColumn(name="niveau01_id", referencedColumnName="id", nullable=false)
*/
private $niveau01;
public function getId(): ?int
{
return $this->id;
}
public function getUser(): ?User
{
return $this->user;
}
public function setUser(?User $user): self
{
$this->user = $user;
return $this;
}
public function getNiveau01(): ?Niveau01
{
return $this->niveau01;
}
public function setNiveau01(?Niveau01 $niveau01): self
{
$this->niveau01 = $niveau01;
return $this;
}
}

45
src/Entity/Whitelist.php Normal file
View File

@ -0,0 +1,45 @@
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* @ORM\Entity
* @ORM\Table(name="whitelist")
* @ORM\HasLifecycleCallbacks()
*
* @UniqueEntity(fields="label", message="Une liste blanche existe déjà avec ce label")
*/
class Whitelist
{
/**
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\Column(type="string", length=250, unique=true)
*/
private $label;
public function getId(): ?int
{
return $this->id;
}
public function getLabel(): ?string
{
return $this->label;
}
public function setLabel(string $label): self
{
$this->label = $label;
return $this;
}
}

View File

@ -0,0 +1,28 @@
<?php
namespace App\EventListener;
use Doctrine\Bundle\DoctrineBundle\EventSubscriber\EventSubscriberInterface;
use Doctrine\ORM\Events;
use Doctrine\Persistence\Event\LifecycleEventArgs;
class AllSubscriber implements EventSubscriberInterface
{
private $entity;
public function getSubscribedEvents(): array
{
return [
Events::preRemove,
];
}
public function preRemove(LifecycleEventArgs $args): void
{
$this->entity = $args->getObject();
// Les enregistrements négatifs sont des enregistrements systeme indispensable
if($this->entity->getId()<0)
throw new \Exception("Impossible de supprimer cet enregistrement. C'est un enregistrement système");
}
}

View File

@ -0,0 +1,138 @@
<?php
namespace App\EventListener;
use Doctrine\ORM\EntityManagerInterface;
use App\Entity\Group as Entity;
use App\Entity\UserGroup as UserGroup;
use Doctrine\Bundle\DoctrineBundle\EventSubscriber\EventSubscriberInterface;
use Doctrine\ORM\Events;
use Doctrine\Persistence\Event\LifecycleEventArgs;
use Ramsey\Uuid\Uuid;
use App\Service\LdapService;
class GroupSubscriber implements EventSubscriberInterface
{
private $em;
private $entity;
private $ldap;
public function __construct(EntityManagerInterface $em,LdapService $ldap)
{
$this->em = $em;
$this->ldap = $ldap;
}
public function getSubscribedEvents(): array
{
return [
Events::postPersist,
Events::preUpdate,
Events::postUpdate,
Events::preRemove,
Events::postRemove,
];
}
public function postPersist(LifecycleEventArgs $args): void
{
$this->entity = $args->getObject();
if (!$this->entity instanceof Entity) return;
// Synchronisation nine2ldap
$this->nine2ldap();
// On s'assure que le propriétaire est bien membre du groupe avec le role manager
$this->ctrlOwner();
}
public function preUpdate(LifecycleEventArgs $args): void
{
$this->entity = $args->getObject();
if (!$this->entity instanceof Entity) return;
}
public function postUpdate(LifecycleEventArgs $args): void
{
$this->entity = $args->getObject();
if (!$this->entity instanceof Entity) return;
// Synchronisation nine2ldap
$this->nine2ldap();
// On s'assure que le propriétaire est bien membre du groupe avec le role manager
$this->ctrlOwner();
}
public function preRemove(LifecycleEventArgs $args): void
{
$this->entity = $args->getObject();
if (!$this->entity instanceof Entity) return;
// Synchronisation nine2ldap
$this->nine2ldapremove();
}
public function postRemove(LifecycleEventArgs $args): void
{
$this->entity = $args->getObject();
if (!$this->entity instanceof Entity) return;
}
private function nine2ldap() {
if($this->ldap->isNine2Ldap()) {
// On s'assure que la structure organisationnelle est présente
$this->ldap->addOrganisations();
// Ajout / Modification group dans annuaire
$filter="gidnumber=".$this->entity->getId();
$attributes=$this->ldap->listAttributesGroup();
$ldapentrys=$this->ldap->search($filter,$attributes,$this->ldap->getParameter("basegroup"));
if(empty($ldapentrys)) {
$this->ldap->addGroup($this->entity);
}
elseif($this->ldap->ismodifyGroup($this->entity,$ldapentrys[0])) {
$this->ldap->modifyGroup($this->entity,$ldapentrys[0]["cn"]);
}
}
}
private function nine2ldapremove() {
if($this->ldap->isNine2Ldap()) {
$filter="gidnumber=".$this->entity->getId();
$attributes=$this->ldap->listAttributesGroup();
$ldapentrys=$this->ldap->search($filter,$attributes,$this->ldap->getParameter("basegroup"));
if(!empty($ldapentrys)) {
$this->ldap->deleteGroup($this->entity);
}
}
}
private function ctrlOwner() {
$group=$this->entity;
// Le propriétaire passe manager
$usergroups=$this->em->getRepository("App\Entity\UserGroup")->findBy(["group"=>$group,"rolegroup"=>"100"]);
foreach($usergroups as $usergroup) {
$usergroup->setRolegroup(90);
$this->em->flush();
}
// Le propriétaire prend son role dans le groupe
if($group->getOwner()) {
$usergroup=$this->em->getRepository("App\Entity\UserGroup")->findOneBy(["group"=>$group,"user"=>$group->getOwner()]);
if(!$usergroup) {
$usergroup=new UserGroup();
$usergroup->setUser($group->getOwner());
$usergroup->setGroup($group);
$usergroup->setApikey(Uuid::uuid4());
}
$usergroup->setRolegroup(100);
$this->em->persist($usergroup);
$this->em->flush();
}
}
}

View File

@ -0,0 +1,118 @@
<?php
namespace App\EventListener;
use Doctrine\ORM\EntityManagerInterface;
use App\Entity\Niveau01 as Entity;
use Doctrine\Bundle\DoctrineBundle\EventSubscriber\EventSubscriberInterface;
use Doctrine\ORM\Events;
use Doctrine\Persistence\Event\LifecycleEventArgs;
use App\Service\LdapService;
class Niveau01Subscriber implements EventSubscriberInterface
{
private $em;
private $entity;
private $ldap;
public function __construct(EntityManagerInterface $em,LdapService $ldap)
{
$this->em = $em;
$this->ldap = $ldap;
}
public function getSubscribedEvents(): array
{
return [
Events::postPersist,
Events::preUpdate,
Events::postUpdate,
Events::preRemove,
Events::postRemove,
];
}
public function postPersist(LifecycleEventArgs $args): void
{
$this->entity = $args->getObject();
if (!$this->entity instanceof Entity) return;
// Synchronisation nine2ldap
$this->nine2ldap();
}
public function preUpdate(LifecycleEventArgs $args): void
{
$this->entity = $args->getObject();
if (!$this->entity instanceof Entity) return;
}
public function postUpdate(LifecycleEventArgs $args): void
{
$this->entity = $args->getObject();
if (!$this->entity instanceof Entity) return;
// Synchronisation nine2ldap
$this->nine2ldap();
}
public function preRemove(LifecycleEventArgs $args): void
{
$this->entity = $args->getObject();
if (!$this->entity instanceof Entity) return;
// Impossible de supprimer si présence de niveau02 rattaché
if(!$this->entity->getNiveau02s()->isEmpty())
throw new \Exception("Impossible de supprimer cet enregistrement. Il est lié à des niveaux de rang 02");
// Impossible de supprimer si présence de registration rattaché
if(!$this->entity->getRegistrations()->isEmpty())
throw new \Exception("Impossible de supprimer cet enregistrement. Il est lié à des inscriptions");
// Impossible de supprimer si présence de user rattaché
if(!$this->entity->getUsers()->isEmpty())
throw new \Exception("Impossible de supprimer cet enregistrement. Il est lié à des utilisateurs");
// Synchronisation nine2ldap
$this->nine2ldapremove();
}
public function postRemove(LifecycleEventArgs $args): void
{
$this->entity = $args->getObject();
if (!$this->entity instanceof Entity) return;
}
private function nine2ldap() {
if($this->ldap->isNine2Ldap()) {
// On s'assure que la structure organisationnelle est présente
$this->ldap->addOrganisations();
// Ajout / Modification dans annuaire
$filter="gidnumber=".$this->entity->getId();
$attributes=$this->ldap->listAttributesNiveau01();
$ldapentrys=$this->ldap->search($filter,$attributes,$this->ldap->getParameter("baseniveau01"));
if(empty($ldapentrys)) {
$this->ldap->addNiveau01($this->entity);
}
elseif($this->ldap->ismodifyNiveau01($this->entity,$ldapentrys[0])) {
$this->ldap->modifyNiveau01($this->entity,$ldapentrys[0]["cn"]);
}
}
}
private function nine2ldapremove() {
if($this->ldap->isNine2Ldap()) {
$filter="gidnumber=".$this->entity->getId();
$attributes=$this->ldap->listAttributesNiveau01();
$ldapentrys=$this->ldap->search($filter,$attributes,$this->ldap->getParameter("baseniveau01"));
if(!empty($ldapentrys)) {
$this->ldap->deleteNiveau01($this->entity);
}
}
}
}

View File

@ -0,0 +1,112 @@
<?php
namespace App\EventListener;
use Doctrine\ORM\EntityManagerInterface;
use App\Entity\Niveau02 as Entity;
use Doctrine\Bundle\DoctrineBundle\EventSubscriber\EventSubscriberInterface;
use Doctrine\ORM\Events;
use Doctrine\Persistence\Event\LifecycleEventArgs;
use App\Service\LdapService;
class Niveau02Subscriber implements EventSubscriberInterface
{
private $em;
private $entity;
private $ldap;
public function __construct(EntityManagerInterface $em,LdapService $ldap)
{
$this->em = $em;
$this->ldap = $ldap;
}
public function getSubscribedEvents(): array
{
return [
Events::postPersist,
Events::preUpdate,
Events::postUpdate,
Events::preRemove,
Events::postRemove,
];
}
public function postPersist(LifecycleEventArgs $args): void
{
$this->entity = $args->getObject();
if (!$this->entity instanceof Entity) return;
// Synchronisation nine2ldap
$this->nine2ldap();
}
public function preUpdate(LifecycleEventArgs $args): void
{
$this->entity = $args->getObject();
if (!$this->entity instanceof Entity) return;
}
public function postUpdate(LifecycleEventArgs $args): void
{
$this->entity = $args->getObject();
if (!$this->entity instanceof Entity) return;
// Synchronisation nine2ldap
$this->nine2ldap();
}
public function preRemove(LifecycleEventArgs $args): void
{
$this->entity = $args->getObject();
if (!$this->entity instanceof Entity) return;
// Impossible de supprimer si présence de registration rattaché
if(!$this->entity->getRegistrations()->isEmpty())
throw new \Exception("Impossible de supprimer cet enregistrement. Il est lié à des inscriptions");
// Impossible de supprimer si présence de user rattaché
if(!$this->entity->getUsers()->isEmpty())
throw new \Exception("Impossible de supprimer cet enregistrement. Il est lié à des utilisateurs");
// Synchronisation nine2ldap
$this->nine2ldapremove();
}
public function postRemove(LifecycleEventArgs $args): void
{
$this->entity = $args->getObject();
if (!$this->entity instanceof Entity) return;;
}
private function nine2ldap() {
if($this->ldap->isNine2Ldap()) {
// On s'assure que la structure organisationnelle est présente
$this->ldap->addOrganisations();
// Ajout / Modification dans annuaire
$filter="gidnumber=".$this->entity->getId();
$attributes=$this->ldap->listAttributesNiveau02();
$ldapentrys=$this->ldap->search($filter,$attributes,$this->ldap->getParameter("baseniveau02"));
if(empty($ldapentrys)) {
$this->ldap->addNiveau02($this->entity);
}
elseif($this->ldap->ismodifyNiveau02($this->entity,$ldapentrys[0])) {
$this->ldap->modifyNiveau02($this->entity,$ldapentrys[0]["cn"]);
}
}
}
private function nine2ldapremove() {
if($this->ldap->isNine2Ldap()) {
$filter="gidnumber=".$this->entity->getId();
$attributes=$this->ldap->listAttributesNiveau02();
$ldapentrys=$this->ldap->search($filter,$attributes,$this->ldap->getParameter("baseniveau02"));
if(!empty($ldapentrys)) {
$this->ldap->deleteNiveau02($this->entity);
}
}
}
}

View File

@ -0,0 +1,67 @@
<?php
namespace App\EventListener;
use Doctrine\ORM\EntityManagerInterface;
use App\Entity\UserGroup as Entity;
use Doctrine\Bundle\DoctrineBundle\EventSubscriber\EventSubscriberInterface;
use Doctrine\ORM\Events;
use Doctrine\Persistence\Event\LifecycleEventArgs;
use App\Service\LdapService;
class UserGroupSubscriber implements EventSubscriberInterface
{
private $em;
private $entity;
private $ldap;
public function __construct(EntityManagerInterface $em,LdapService $ldap)
{
$this->em = $em;
$this->ldap = $ldap;
}
public function getSubscribedEvents(): array
{
return [
Events::postPersist,
Events::preRemove,
];
}
public function postPersist(LifecycleEventArgs $args): void
{
$this->entity = $args->getObject();
if (!$this->entity instanceof Entity) return;
// Synchronisation nine2ldap
$this->nine2ldap();
}
public function preRemove(LifecycleEventArgs $args): void
{
$this->entity = $args->getObject();
if (!$this->entity instanceof Entity) return;
// Synchronisation nine2ldap
$this->nine2ldapremove();
}
private function nine2ldap() {
if($this->ldap->isNine2Ldap()) {
// On s'assure que la structure organisationnelle est présente
$this->ldap->addOrganisations();
// Ajout / Modification dans annuaire
$this->ldap->addUserGroup($this->entity);
}
}
private function nine2ldapremove() {
if($this->ldap->isNine2Ldap()) {
$this->ldap->delUserGroup($this->entity);
}
}
}

View File

@ -0,0 +1,126 @@
<?php
namespace App\EventListener;
use Doctrine\ORM\EntityManagerInterface;
use App\Entity\User as Entity;
use App\Entity\UserGroup as UserGroup;
use Doctrine\Bundle\DoctrineBundle\EventSubscriber\EventSubscriberInterface;
use Doctrine\ORM\Events;
use Doctrine\Persistence\Event\LifecycleEventArgs;
use Ramsey\Uuid\Uuid;
use App\Service\LdapService;
class UserSubscriber implements EventSubscriberInterface
{
private $em;
private $entity;
private $ldap;
public function __construct(EntityManagerInterface $em,LdapService $ldap)
{
$this->em = $em;
$this->ldap = $ldap;
}
public function getSubscribedEvents(): array
{
return [
Events::postPersist,
Events::preUpdate,
Events::postUpdate,
Events::preRemove,
Events::postRemove,
];
}
public function postPersist(LifecycleEventArgs $args): void
{
$this->entity = $args->getObject();
if (!$this->entity instanceof Entity) return;
// Synchronisation nine2ldap
$this->nine2ldap();
// Recherche du group tout le monde
$group=$this->em->getRepository("App\Entity\Group")->find(-1);
$usergroup=new UserGroup();
$usergroup->setUser($this->entity);
$usergroup->setGroup($group);
$usergroup->setApikey(Uuid::uuid4());
$usergroup->setRolegroup(0);
$this->em->persist($usergroup);
$this->em->flush();
}
public function preUpdate(LifecycleEventArgs $args): void
{
$this->entity = $args->getObject();
if (!$this->entity instanceof Entity) return;
}
public function postUpdate(LifecycleEventArgs $args): void
{
$this->entity = $args->getObject();
if (!$this->entity instanceof Entity) return;
// Synchronisation nine2ldap
$this->nine2ldap();
if (!$this->entity instanceof Entity) return;
}
public function preRemove(LifecycleEventArgs $args): void
{
$this->entity = $args->getObject();
if (!$this->entity instanceof Entity) return;
// Synchronisation nine2ldap
$this->nine2ldapremove();
}
public function postRemove(LifecycleEventArgs $args): void
{
$this->entity = $args->getObject();
if (!$this->entity instanceof Entity) return;;
}
private function nine2ldap() {
if($this->ldap->isNine2Ldap()) {
// On s'assure que la structure organisationnelle est présente
$this->ldap->addOrganisations();
// Ajout / Modification dans annuaire
$filter=str_replace("*",$this->entity->getUsername(),$this->ldap->getParameter("filteruser"));
$attributes=$this->ldap->listAttributesNiveau02();
$ldapentrys=$this->ldap->search($filter,$attributes,$this->ldap->getParameter("baseuser"));
if(empty($ldapentrys)) {
$this->ldap->addUser($this->entity);
}
elseif($this->ldap->ismodifyUser($this->entity,$ldapentrys[0])) {
$this->ldap->modifyUser($this->entity,$ldapentrys[0]["cn"]);
}
// Mise à jour des niveaux du user
$this->ldap->updateNiveauUser($this->entity);
}
}
private function nine2ldapremove() {
if($this->ldap->isNine2Ldap()) {
$filter=str_replace("*",$this->entity->getUsername(),$this->ldap->getParameter("filteruser"));
$attributes=$this->ldap->listAttributesNiveau02();
$ldapentrys=$this->ldap->search($filter,$attributes,$this->ldap->getParameter("baseuser"));
if(!empty($ldapentrys)) {
$this->ldap->deleteUser($this->entity);
}
// Mise à jour des niveaux du user en forçant le détachement
$this->ldap->updateNiveauUser($this->entity,true);
}
}
}

189
src/Form/ConfigType.php Normal file
View File

@ -0,0 +1,189 @@
<?php
namespace App\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use FOS\CKEditorBundle\Form\Type\CKEditorType;
class ConfigType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('submit',
SubmitType::class,[
"label" => "Valider",
"attr" => ["class" => "btn btn-success"],
]
);
$builder->add('id',
TextType::class,
array("label" =>"Clé",
'disabled' => true));
switch($options["type"]) {
case "string":
$builder->add('value',
TextType::class,
array("label" => "Valeur",
'required' => ($options["required"]==0?false:true)));
break;
case "boolean":
$choices=["oui" => "1","non" => "0"];
$builder->add("value", ChoiceType::class,
array("label" =>"Valeur",
'required' => ($options["required"]==0?false:true),
"choices" => $choices));
break;
case "integer":
$builder->add("value",
IntegerType::class, [
"label" =>"Valeur",
"attr" => ["min" => "0"],
"required" => ($options["required"]==0?false:true),
]
);
break;
case "pourcentage":
$builder->add("value",
IntegerType::class, [
"label" =>"Valeur",
"attr" => ["min" => "0", "max"=>"100"],
"required" => ($options["required"]==0?false:true),
]
);
break;
case "font":
$choices=[
"ABeeZee-Regular" => "ABeeZee-Regular",
"Acme-Regular" => "Acme-Regular",
"AlfaSlabOne-Regular" => "AlfaSlabOne-Regular",
"Anton-Regular" => "Anton-Regular",
"Baloo-Regular" => "Baloo-Regular",
"CarterOne-Regular" => "CarterOne-Regular",
"Chewy-Regular" => "Chewy-Regular",
"Courgette-Regular" => "Courgette-Regular",
"FredokaOne-Regular" => "FredokaOne-Regular",
"Grandstander" => "Grandstander",
"Helvetica" => "Helvetica",
"Justanotherhand-Regular" => "Justanotherhand-Regular",
"Lato-Regular" => "Lato-Regular",
"LexendDeca-Regular" => "LexendDeca-Regular",
"LuckiestGuy-Regular" => "LuckiestGuy-Regular",
"Overpass-Black" => "Overpass-Black",
"PassionOne" => "PassionOne",
"Peacesans" => "Peacesans",
"Redressed" => "Redressed",
"Righteous-Regular" => "Righteous-Regular",
"Roboto-Regular" => "Roboto-Regular",
"RubikMonoOne-Regular" => "RubikMonoOne-Regular",
"SigmarOne-Regular" => "SigmarOne-Regular",
"Signika-Regular" => "Signika-Regular",
"Teko-Bold" => "Teko-Bold",
"Theboldfont" => "Theboldfont",
"Viga-Regular" => "Viga-Regular",
];
$builder->add("value", ChoiceType::class,
array("label" =>"Valeur",
'required' => ($options["required"]==0?false:true),
"choices" => $choices));
break;
case "editor":
$builder->add('value',
CKEditorType::class,[
"required" => ($options["required"]==0?false:true),
"config_name" => "full_config",
"config" => [
'height' => 600,
'filebrowserUploadRoute' => 'app_ckeditor_upload',
]
]
);
break;
case "role":
$choices=array(
"NO_BODY" => "NO_BODY",
"ROLE_USER" => "ROLE_USER",
"ROLE_MASTER" => "ROLE_MASTER",
"ROLE_MODO" => "ROLE_MODO",
);
$builder->add("value", ChoiceType::class,
array("label" =>"Valeur",
"label_attr" => array("style" => 'margin-top:15px;'),
"attr" => array("class" => "form-control"),
'required' => ($options["required"]==0?false:true),
"choices" => $choices));
break;
case "scopeannu":
$choices=array(
"ALL" => "ALL",
"SAME_NIVEAU01" => "SAME_NIVEAU01",
"SAME_NIVEAU02" => "SAME_NIVEAU02",
);
$builder->add("value", ChoiceType::class,
array("label" =>"Valeur",
"label_attr" => array("style" => 'margin-top:15px;'),
"attr" => array("class" => "form-control"),
'required' => ($options["required"]==0?false:true),
"choices" => $choices));
break;
case "logo":
$builder->add('value',HiddenType::class);
break;
case "header":
$builder->add('value',HiddenType::class);
break;
case "image":
$builder->add('value',HiddenType::class);
break;
case "color":
$builder->add('value',
TextType::class,
array("label" => "Valeur",
"attr" => ["class" => "pick-a-color"],
'required' => ($options["required"]==0?false:true)));
break;
}
$builder->add('help',
TextareaType::class,
array("label" =>"Aide",
"attr" => ["style" => "height: 200px;"],
'required' => false,
'disabled' => true));
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'App\Entity\Config',
'mode' => "string",
'id' => "string",
'type' => "string",
'required' => "string",
));
}
}

66
src/Form/CronType.php Normal file
View File

@ -0,0 +1,66 @@
<?php
namespace App\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\DateTimeType;
class CronType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('submit', SubmitType::class, [
"label" => "Valider",
"attr" => array("class" => "btn btn-success")
])
->add('command', TextType::class, [
'label' => 'Commande',
"disabled" => true,
])
->add('jsonargument', TextType::class, [
'label' => 'Argument Commande au format json',
"disabled" => true,
])
->add('statut', ChoiceType::class, [
'label' => "Statut",
'choices' => array("Désactivé" => -1,"KO" => "0","OK" => "1")
])
->add('repeatinterval', IntegerType::class, [
'label' => "Interval en seconde entre deux éxécution"
])
->add('nextexecdate', DatetimeType::class, [
'label' => "Prochaine exécution",
'widget' => 'single_text',
"html5"=>true,
'input_format' => "d/m/Y H:i"
])
;
}
/**
* @param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => 'App\Entity\Cron',
'mode' => 'string'
]);
}
}

142
src/Form/GroupType.php Normal file
View File

@ -0,0 +1,142 @@
<?php
namespace App\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Tetranz\Select2EntityBundle\Form\Type\Select2EntityType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\EntityManager;
class GroupType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('submit',
SubmitType::class,[
"label" => "Valider",
"attr" => ["class" => "btn btn-success"],
]
);
if($options["access"]=="admin") {
$builder->add('isworkgroup',
ChoiceType::class,[
"label" =>"Groupe de Travail",
"choices" => ["non" => "0","oui" => "1"],
]
);
}
if($options["access"]=="admin" || $options["mode"] == "update") {
$builder->add('owner',
Select2EntityType::class, [
"label" => "Propriétaire",
"required" => false,
"multiple" => false,
"remote_route" => 'app_'.$options["access"].'_user_selectlist',
"class" => 'App\Entity\User',
"primary_key" => 'id',
"text_property" => 'username',
"minimum_input_length" => 2,
"page_limit" => 10,
"allow_clear" => true,
"delay" => 250,
"cache" => false,
"cache_timeout" => 60000, // if 'cache' is true
"language" => 'fr',
"placeholder" => 'Selectionner un propriétaire',
]
);
}
if($options["access"]=="admin") {
$builder->add('email',
EmailType::class, [
"label" => "Mail",
"required" => false,
]
);
}
$builder->add("description",
TextareaType::class, [
"label" => 'Description',
"required" => false,
"attr" => ["rows" => '4'],
]
);
$builder->add('label',
TextType::class, [
"label" =>"Label",
]
);
$builder->add("isopen",
ChoiceType::class,array(
"label" =>"Groupe Ouvert (inscription possible par les utilisateurs)",
"choices" => ["non" => "0","oui" => "1"],
)
);
// Si masteridentity = LDAP alors on demande le filtre des utilisateurs qui appartiennent à ce groupe
if($options["appMasteridentity"]=="LDAP"&&$options["access"]=="admin")
{
$builder->add("fgassoc",
ChoiceType::class,[
"mapped" => false,
"label" => "Groupe associé à l'annuaire ?",
"choices" => ["non" => "0","oui" => "1"],
]
);
$builder->add('ldapfilter',
TextType::class, [
"label" => "Filtre LDAP des utilisateurs",
"label_attr" => ["id" => "label_group_ldapfilter"],
"required" => false,
]
);
}
if($options["appMasteridentity"]=="SSO"&&$options["access"]=="admin")
{
$builder->add("fgassoc",
ChoiceType::class,[
"mapped" => false,
"label" => "Groupe associé à des attributs SSO ?",
"choices" => ["non" => "0","oui" => "1"],
]
);
$builder->add('attributes',
TextareaType::class, [
"label" => "Attributs SSO des utilisateurs",
"label_attr" => ["id" => "label_group_attributes"],
"required" => false,
"attr" => ["rows" => 10]
]
);
}
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'App\Entity\Group',
'mode' => "string",
'access' => "string",
'appMasteridentity' => "string",
));
}
}

37
src/Form/LoginType.php Normal file
View File

@ -0,0 +1,37 @@
<?php
namespace App\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
class LoginType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('submit',
SubmitType::class,[
"label" => "Valider",
"attr" => ["class" => "btn btn-success mt-4 float-end"],
]
);
$builder->add('username',
TextType::class,[
"label" =>"Login",
"attr" => ["autocomplete" => "new-password"]
]
);
$builder->add('password',
PasswordType::class, [
"always_empty" => true,
"label" => "Mot de Passe",
"attr" => ["autocomplete" => "new-password"]
]
);
}
}

81
src/Form/Niveau01Type.php Normal file
View File

@ -0,0 +1,81 @@
<?php
namespace App\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
class Niveau01Type extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('submit',
SubmitType::class,[
"label" => "Valider",
"attr" => ["class" => "btn btn-success"],
]
);
$builder->add('label',
TextType::class, [
"label" =>"Label",
]
);
// Si masteridentity = LDAP alors on demande le filtre des utilisateurs qui appartiennent à ce groupe
if($options["appMasteridentity"]=="LDAP"||$options["appSynchro"]=="LDAP2NINE")
{
$builder->add("fgassocldap",
ChoiceType::class,[
"mapped" => false,
"label" => $options["appNiveau01label"]." associé à l'annuaire ?",
"choices" => ["non" => "0","oui" => "1"],
]
);
$builder->add('ldapfilter',
TextType::class, [
"label" => "Filtre LDAP du ".$options["appNiveau01label"],
"label_attr" => ["id" => "label_group_ldapfilter"],
"required" => false,
]
);
}
if($options["appMasteridentity"]=="SSO")
{
$builder->add("fgassocsso",
ChoiceType::class,[
"mapped" => false,
"label" => $options["appNiveau01label"]." associé à des attributs SSO ?",
"choices" => ["non" => "0","oui" => "1"],
]
);
$builder->add('attributes',
TextareaType::class, [
"label" => "Attributs SSO du ".$options["appNiveau01label"],
"label_attr" => ["id" => "label_group_attributes"],
"required" => false,
"attr" => ["rows" => 10]
]
);
}
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'App\Entity\Niveau01',
'mode' => "string",
'appMasteridentity' => "string",
"appSynchro" => "string",
'appNiveau01label' => "string"
));
}
}

70
src/Form/Niveau02Type.php Normal file
View File

@ -0,0 +1,70 @@
<?php
namespace App\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Query\Expr\Join;
class Niveau02Type extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('submit',
SubmitType::class,[
"label" => "Valider",
"attr" => ["class" => "btn btn-success"],
]
);
$access=$options["access"];
$userid=$options["userid"];
$builder->add('niveau01',
EntityType::class, [
"class" => "App\Entity\Niveau01",
"label" => $options["appNiveau01label"],
"placeholder" => "== Choisir ".$options["appNiveau01label"]." ==",
"choice_label" => "label",
"disabled" => ($options["mode"]!="submit"),
"query_builder"=> function (EntityRepository $er) use($access,$userid) {
switch($access) {
case "admin":
return $er->createQueryBuilder('niveau01')->orderBy('niveau01.label','ASC');
break;
case "modo":
$result=$er->createQueryBuilder("table")->innerJoin("App:UserModo", "usermodo", Join::WITH, "table.id = usermodo.niveau01")->orderBy('table.label','ASC');
$result->andWhere("usermodo.user = :user");
$result->setParameter('user', $userid);
return $result;
break;
}
},
]
);
$builder->add('label',
TextType::class, [
"label" =>"Label",
]
);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'App\Entity\Niveau02',
'mode' => "string",
'access' => "string",
'userid' => "string",
'appMasteridentity' => "string",
'appNiveau01label' => "string",
'appNiveau02label' => "string"
));
}
}

View File

@ -0,0 +1,212 @@
<?php
namespace App\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Gregwar\CaptchaBundle\Type\CaptchaType;
use Tetranz\Select2EntityBundle\Form\Type\Select2EntityType;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Query\Expr\Join;
class RegistrationType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('submit',
SubmitType::class,[
"label" => ($options["mode"]=="submit"?"Confirmer":"Enregistrer et envoyer le mail de confirmation"),
"attr" => ["class" => "btn btn-success"],
]
);
if($options["mode"]=="update") {
$builder->add('save',
SubmitType::class, array(
"label" => "Enregistrer sans envoyer le mail de confirmation",
"attr" => array("class" => "btn btn-success")
)
);
$builder->add('note',
TextareaType::class, array(
"label" => "Notes Administrateur",
"required" => false,
"disabled" => ($options["mode"]=="delete"?true:false),
"attr" => array("class" => "form-control", "style" => "margin-bottom:15px; height: 130px")
)
);
}
$builder->add('username',
TextType::class,[
"label" =>"Login",
"disabled" => ($options["mode"]!="submit"),
"attr" => ["autocomplete" => "new-password"]
]
);
$builder->add('lastname',
TextType::class, [
"label" =>"Nom",
"disabled" => ($options["appMasteridentity"]!="SQL"&&$options["mode"]!="submit"),
]
);
$builder->add('firstname',
TextType::class, [
"label" =>"Prénom",
"disabled" => ($options["appMasteridentity"]!="SQL"&&$options["mode"]!="submit"),
]
);
$builder->add('email',
EmailType::class, array(
"label" =>"Mail",
"disabled" => ($options["appMasteridentity"]!="SQL")&&$options["mode"]!="submit",
)
);
$access=$options["access"];
$userid=$options["userid"];
$builder->add('niveau01',
EntityType::class, [
"class" => "App\Entity\Niveau01",
"label" => $options["appNiveau01label"],
"placeholder" => "== Choisir ".$options["appNiveau01label"]." ==",
"choice_label" => "label",
"disabled" => ($options["appMasteridentity"]!="SQL"&&$options["mode"]!="submit"),
"query_builder"=> function (EntityRepository $er) use($access,$userid) {
switch($access) {
case "admin":
return $er->createQueryBuilder('niveau01')->orderBy('niveau01.label','ASC');
break;
case "modo":
$result=$er->createQueryBuilder("table")->innerJoin("App:UserModo", "usermodo", Join::WITH, "table.id = usermodo.niveau01")->orderBy('table.label','ASC');
$result->andWhere("usermodo.user = :user");
$result->setParameter('user', $userid);
return $result;
break;
default:
return $er->createQueryBuilder('niveau01')->orderBy('niveau01.label','ASC');
break;
}
},
]
);
$builder->add('niveau02',
Select2EntityType::class, [
"label" => $options["appNiveau02label"],
"required" => false,
"remote_route" => "app_niveau02_selectlist",
"class" => "App\Entity\Niveau02",
//"req_params" => ["niveau01" => "parent.children[niveau01]"],
"primary_key" => "id",
"text_property" => "label",
"minimum_input_length" => 0,
"page_limit" => 10,
"allow_clear" => true,
"delay" => 250,
"cache" => false,
"cache_timeout" => 60000,
"language" => "fr",
"placeholder" => "== Choisir ".$options["appNiveau02label"]." ==",
]
);
# Password
if($options["mode"]=="submit") {
$builder->add('password',
RepeatedType::class, array(
"type" => PasswordType::class,
"required" => ($options["mode"]=="submit"?true:false),
"first_options" => array("label" => "Mot de Passe","attr" => array("class" => "form-control", "style" => "margin-bottom:15px", "autocomplete" => "new-password")),
"second_options" => array('label' => 'Confirmer Mot de Passe',"attr" => array("class" => "form-control", "style" => "margin-bottom:15px")),
"invalid_message" => "Mot de passe non valide"
)
);
$builder->add('passwordplain',PasswordType::class,["mapped"=>false,"required"=>false]);
$builder->add('captcha',
CaptchaType::class,array(
"width" => 200,
"height" => 50,
"length" => 6,
)
);
}
$choices=array("oui" => "1","non" => "0");
$builder->add("isvisible",
ChoiceType::class,array(
"label" =>"Visible",
"choices" => $choices
)
);
$builder->add('postaladress',
TextareaType::class, [
"label" => "Adresse",
"required" => false,
"attr" => ["style" => "height:90px"]
]
);
$builder->add('telephonenumber',
TextType::class, [
"label" => "Téléphone",
"required" => false,
]
);
$builder->add('job',
TextType::class, [
"label" => "Métier",
"required" => false,
]
);
$builder->add('position',
TextType::class, [
"label" => "Fonction",
"required" => false,
]
);
$builder->add('motivation',
TextareaType::class, [
"label" => "Motivation",
"required" => false,
"attr" => ["style" => "height: 90px"],
]
);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'App\Entity\Registration',
'mode' => "string",
'access' => "string",
'userid' => "string",
'appMasteridentity' => "string",
'appNiveau01label' => "string",
'appNiveau02label' => "string",
));
}
}

55
src/Form/ResetpwdType.php Normal file
View File

@ -0,0 +1,55 @@
<?php
namespace App\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
class ResetpwdType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('submit',
SubmitType::class,[
"label" => "Valider",
"attr" => ["class" => "btn btn-success"],
]
);
if($options["mode"]=="resetpwd01") {
$builder->add('email',
TextType::class, array(
"label" =>"Votre Mail",
"disabled" => ($options["mode"]=="delete"?true:false),
"attr" => array("class" => "form-control", "style" => "margin-bottom:15px")
)
);
}
else {
$builder->add('password',
RepeatedType::class, array(
"type" => PasswordType::class,
"required" => ($options["mode"]=="submit"?true:false),
"options" => array("always_empty" => true),
"first_options" => array("label" => "Votre nouveau Mot de Passe","attr" => array("class" => "form-control", "style" => "margin-bottom:15px")),
"second_options" => array('label' => 'Confirmer votre nouveau Mot de Passe',"attr" => array("class" => "form-control", "style" => "margin-bottom:15px")),
"invalid_message" => "Mot de passe non valide"
)
);
$builder->add('passwordplain',PasswordType::class,["mapped"=>false,"required"=>false]);
}
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'App\Entity\User',
'mode' => "string"
));
}
}

232
src/Form/UserType.php Normal file
View File

@ -0,0 +1,232 @@
<?php
namespace App\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\DateTimeType;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Tetranz\Select2EntityBundle\Form\Type\Select2EntityType;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Query\Expr\Join;
class UserType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('submit',
SubmitType::class,[
"label" => "Valider",
"attr" => ["class" => "btn btn-success"],
]
);
$builder->add('username',
TextType::class,[
"label" =>"Login",
"disabled" => ($options["mode"]!="submit"),
"attr" => ["autocomplete" => "new-password"]
]
);
if($options["appMasteridentity"]=="SQL"||$options["mode"]=="submit") {
$builder->add('password',
RepeatedType::class, [
"type" => PasswordType::class,
"required" => ($options["mode"]=="submit"),
"options" => ["always_empty" => true],
"first_options" => ["label" => "Mot de Passe","attr" => ["autocomplete" => "new-password"]],
"second_options" => ["label" => 'Confirmer Mot de Passe'],
"invalid_message" => "Mot de passe non valide"
]
);
$builder->add('passwordplain',PasswordType::class,["mapped"=>false,"required"=>false]);
}
$builder->add('lastname',
TextType::class, [
"label" =>"Nom",
"disabled" => ($options["appMasteridentity"]!="SQL"&&$options["mode"]!="submit"),
]
);
$builder->add('firstname',
TextType::class, [
"label" =>"Prénom",
"disabled" => ($options["appMasteridentity"]!="SQL"&&$options["mode"]!="submit"),
]
);
$builder->add('email',
EmailType::class, array(
"label" =>"Mail",
"disabled" => ($options["appMasteridentity"]!="SQL")&&$options["mode"]!="submit",
)
);
$access=$options["access"];
$userid=$options["userid"];
$builder->add('niveau01',
EntityType::class, [
"class" => "App\Entity\Niveau01",
"label" => $options["appNiveau01label"],
"placeholder" => "== Choisir ".$options["appNiveau01label"]." ==",
"choice_label" => "label",
"disabled" => ($options["appMasteridentity"]!="SQL"&&$options["mode"]!="submit"),
"query_builder"=> function (EntityRepository $er) use($access,$userid) {
switch($access) {
case "admin":
return $er->createQueryBuilder('niveau01')->orderBy('niveau01.label','ASC');
break;
case "modo":
$result=$er->createQueryBuilder("table")->innerJoin("App:UserModo", "usermodo", Join::WITH, "table.id = usermodo.niveau01")->orderBy('table.label','ASC');
$result->andWhere("usermodo.user = :user");
$result->setParameter('user', $userid);
return $result;
break;
default:
return $er->createQueryBuilder('niveau01')->orderBy('niveau01.label','ASC');
break;
}
},
]
);
$builder->add('niveau02',
Select2EntityType::class, [
"label" => $options["appNiveau02label"],
"required" => false,
"remote_route" => "app_niveau02_selectlist",
"class" => "App\Entity\Niveau02",
//"req_params" => ["niveau01" => "parent.children[niveau01]"],
"primary_key" => "id",
"text_property" => "label",
"minimum_input_length" => 0,
"page_limit" => 10,
"allow_clear" => true,
"delay" => 250,
"cache" => false,
"cache_timeout" => 60000,
"language" => "fr",
"placeholder" => "== Choisir ".$options["appNiveau02label"]." ==",
]
);
$choices=array("oui" => "1","non" => "0");
$builder->add("isvisible",
ChoiceType::class,array(
"label" =>"Visible",
"choices" => $choices
)
);
$builder->add('postaladress',
TextareaType::class, [
"label" => "Adresse",
"required" => false,
"attr" => ["style" => "height:90px"]
]
);
$builder->add('telephonenumber',
TextType::class, [
"label" => "Téléphone",
"required" => false,
]
);
$builder->add('job',
TextType::class, [
"label" => "Métier",
"required" => false,
]
);
$builder->add('position',
TextType::class, [
"label" => "Fonction",
"required" => false,
]
);
$builder->add('visitedate',
DateTimeType::class, [
"label" => "Date de dernière visite",
"disabled" => true,
"required" => false,
"widget" => 'single_text',
]
);
$builder->add('visitecpt',
IntegerType::class, [
"label" => "Nombre de visites",
"disabled" => true,
"required" => false,
]
);
$builder->add('motivation',
TextareaType::class, [
"label" => "Motivation",
"required" => false,
"attr" => ["style" => "height: 90px"],
]
);
$builder->add('avatar',HiddenType::class);
$builder->add('linkgroups',HiddenType::class, array("mapped" => false));
$builder->add('linkmodos',HiddenType::class, array("mapped" => false));
if($options["access"]=="admin" || $options["access"]=="modo") {
$choices=array("ROLE_ADMIN" => "ROLE_ADMIN","ROLE_MODO" => "ROLE_MODO","ROLE_MASTER" => "ROLE_MASTER","ROLE_USER" => "ROLE_USER");
$builder->add("roles",
ChoiceType::class,[
"label" =>"Rôle",
"required" => true,
"multiple" => true,
"expanded" => true,
"choices" => $choices
]
);
$builder->add('note',
TextareaType::class, [
"label" => "Notes Administrateur",
"required" => false,
"attr" => ["style" => "height: 130px"]
]
);
}
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'App\Entity\User',
'mode' => "string",
'access' => "string",
'userid' => "string",
'appMasteridentity' => "string",
'appNiveau01label' => "string",
'appNiveau02label' => "string",
));
}
}

View File

@ -0,0 +1,35 @@
<?php
namespace App\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
class WhitelistType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('submit',
SubmitType::class,[
"label" => "Valider",
"attr" => ["class" => "btn btn-success"],
]
);
$builder->add('label',
TextType::class, [
"label" =>"Label",
]
);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'App\Entity\Whitelist',
'mode' => "string"
));
}
}

11
src/Kernel.php Normal file
View File

@ -0,0 +1,11 @@
<?php
namespace App;
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Component\HttpKernel\Kernel as BaseKernel;
class Kernel extends BaseKernel
{
use MicroKernelTrait;
}

0
src/Repository/.gitignore vendored Normal file
View File

View File

@ -0,0 +1,33 @@
<?php
namespace App\Repository;
use App\Entity\Config;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
class ConfigRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Config::class);
}
public function add(Config $entity, bool $flush = false): void
{
$this->getEntityManager()->persist($entity);
if ($flush) {
$this->getEntityManager()->flush();
}
}
public function remove(Config $entity, bool $flush = false): void
{
$this->getEntityManager()->remove($entity);
if ($flush) {
$this->getEntityManager()->flush();
}
}
}

View File

@ -0,0 +1,51 @@
<?php
namespace App\Repository;
use App\Entity\Cron;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
class CronRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Cron::class);
}
public function add(Cron $entity, bool $flush = false): void
{
$this->getEntityManager()->persist($entity);
if ($flush) {
$this->getEntityManager()->flush();
}
}
public function remove(Cron $entity, bool $flush = false): void
{
$this->getEntityManager()->remove($entity);
if ($flush) {
$this->getEntityManager()->flush();
}
}
public function toExec()
{
// Les commandes à executer
// = statut = 0 (à executer)
// = statut = 2 (OK) et derniere execution + interval > now et nombre d'appel = 0
// = statut = 3 (KO) et derniere execution + interval > now et nombre d'appel = 0
// = statut = 3 (KO) et nombre d'execution < nombre d'appel
$now=new \DateTime();
$qb = $this->createQueryBuilder('cron')
->Where('cron.statut=0')
->orWhere('(cron.statut=0 OR cron.statut=1) AND cron.nextexecdate<:now');
return $qb->getQuery()->setParameter('now',$now->format("Y-m-d H:i:s"))->getResult();
}
}

View File

@ -0,0 +1,98 @@
<?php
namespace App\Repository;
use App\Entity\Group;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
use Doctrine\Common\Collections\ArrayCollection;
use App\Entity\UserGroup;
use Ramsey\Uuid\Uuid;
class GroupRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Group::class);
}
public function add(Group $entity, bool $flush = false): void
{
$this->getEntityManager()->persist($entity);
if ($flush) {
$this->getEntityManager()->flush();
}
}
public function remove(Group $entity, bool $flush = false): void
{
$this->getEntityManager()->remove($entity);
if ($flush) {
$this->getEntityManager()->flush();
}
}
/* Déterminer les groupes d'un user SSO en fonction de ses attributs */
public function calculateSSOGroup($user,$attruser)
{
$groups = $this->_em->getRepository('App\Entity\Group')->findAll();
$retgroups= new ArrayCollection();
foreach($groups as $group) {
if($group->getAttributes()) {
$attgroup=json_decode($group->getAttributes(),true);
foreach($attgroup as $key => $value) {
if(array_key_exists($key,$attruser)) {
if(is_array($attruser[$key])) {
foreach($attruser[$key] as $val) {
if($value=="*")
$retgroups->add($group);
elseif($val==$value)
$retgroups->add($group);
}
}
else {
if($value=="*")
$retgroups->add($group);
elseif($value==$attruser[$key])
$retgroups->add($group);
}
}
}
}
}
// Pour chaque groupe de l'utilisateur
$usergroups=$user->getGroups();
// On le détache des groupes auxquelles il n'appartient plus
if($usergroups) {
foreach($usergroups as $usergroup) {
if($usergroup->getGroup()->getAttributes()!="") {
if(!$retgroups->contains($usergroup->getGroup())) {
$user->removeGroup($usergroup);
}
}
}
}
// On attache le user aux groupes
foreach($retgroups as $retgroup) {
$usergroup=$this->_em->getRepository('App\Entity\UserGroup')->findBy(["user"=>$user,"group"=>$retgroup]);
if(!$usergroup) {
$usergroup=new UserGroup();
$usergroup->setUser($user);
$usergroup->setGroup($retgroup);
$usergroup->setApikey(Uuid::uuid4());
$usergroup->setRolegroup(0);
$this->_em->persist($usergroup);
$this->_em->flush();
}
}
return $user;
}
}

View File

@ -0,0 +1,83 @@
<?php
namespace App\Repository;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
use App\Entity\Niveau01;
use App\Service\LdapService;
class Niveau01Repository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry, LdapService $ldapservice)
{
parent::__construct($registry, Niveau01::class);
$this->ldapservice=$ldapservice;
}
public function add(Niveau01 $entity, bool $flush = false): void
{
$this->getEntityManager()->persist($entity);
if ($flush) {
$this->getEntityManager()->flush();
}
}
public function remove(Niveau01 $entity, bool $flush = false): void
{
$this->getEntityManager()->remove($entity);
if ($flush) {
$this->getEntityManager()->flush();
}
}
/* Déterminer le niveau01 d'un user SSO en fonction de ses attributs */
public function calculateSSONiveau01($attruser)
{
$niveau01s = $this->_em->getRepository('App\Entity\Niveau01')->findAll();
foreach($niveau01s as $niveau01) {
if($niveau01->getAttributes()) {
$attniveau=json_decode($niveau01->getAttributes(),true);
foreach($attniveau as $key => $value) {
if(array_key_exists($key,$attruser)) {
if(is_array($attruser[$key])) {
foreach($attruser[$key] as $val) {
if($value=="*")
return $niveau01;
elseif($val==$value)
return $niveau01;
}
}
else {
if($value=="*")
return $niveau01;
elseif($value==$attruser[$key])
return $niveau01;
}
}
}
}
}
return false;
}
/* Déterminer le niveau01 d'un user LDAP */
public function calculateLDAPNiveau01($username)
{
$niveau01s = $this->_em->getRepository('App\Entity\Niveau01')->findAll();
foreach($niveau01s as $niveau01) {
if($niveau01->getLdapfilter()) {
$ismember=$this->ldapservice->findNiveau01ismember($niveau01->getLdapfilter(),$username);
if($ismember) return $niveau01;
}
}
return false;
}
}

View File

@ -0,0 +1,33 @@
<?php
namespace App\Repository;
use App\Entity\Niveau02;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
class Niveau02Repository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Niveau02::class);
}
public function add(Niveau02 $entity, bool $flush = false): void
{
$this->getEntityManager()->persist($entity);
if ($flush) {
$this->getEntityManager()->flush();
}
}
public function remove(Niveau02 $entity, bool $flush = false): void
{
$this->getEntityManager()->remove($entity);
if ($flush) {
$this->getEntityManager()->flush();
}
}
}

View File

@ -0,0 +1,33 @@
<?php
namespace App\Repository;
use App\Entity\Registration;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
class RegistrationRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Registration::class);
}
public function add(Registration $entity, bool $flush = false): void
{
$this->getEntityManager()->persist($entity);
if ($flush) {
$this->getEntityManager()->flush();
}
}
public function remove(Registration $entity, bool $flush = false): void
{
$this->getEntityManager()->remove($entity);
if ($flush) {
$this->getEntityManager()->flush();
}
}
}

View File

@ -0,0 +1,33 @@
<?php
namespace App\Repository;
use App\Entity\Statistic;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
class StatisticRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Statistic::class);
}
public function add(Statistic $entity, bool $flush = false): void
{
$this->getEntityManager()->persist($entity);
if ($flush) {
$this->getEntityManager()->flush();
}
}
public function remove(Statistic $entity, bool $flush = false): void
{
$this->getEntityManager()->remove($entity);
if ($flush) {
$this->getEntityManager()->flush();
}
}
}

View File

@ -0,0 +1,33 @@
<?php
namespace App\Repository;
use App\Entity\UserGroup;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
class UserGroupRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, UserGroup::class);
}
public function add(UserGroup $entity, bool $flush = false): void
{
$this->getEntityManager()->persist($entity);
if ($flush) {
$this->getEntityManager()->flush();
}
}
public function remove(UserGroup $entity, bool $flush = false): void
{
$this->getEntityManager()->remove($entity);
if ($flush) {
$this->getEntityManager()->flush();
}
}
}

View File

@ -0,0 +1,33 @@
<?php
namespace App\Repository;
use App\Entity\User;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
class UserRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, User::class);
}
public function add(User $entity, bool $flush = false): void
{
$this->getEntityManager()->persist($entity);
if ($flush) {
$this->getEntityManager()->flush();
}
}
public function remove(User $entity, bool $flush = false): void
{
$this->getEntityManager()->remove($entity);
if ($flush) {
$this->getEntityManager()->flush();
}
}
}

View File

@ -0,0 +1,89 @@
<?php
namespace App\Service;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
class ApiService
{
private $params;
public function __construct(ParameterBagInterface $params)
{
$this->params = $params;
}
public function setbody(Array $array)
{
return \Unirest\Request\Body::json($array);
}
public function run($method,$url,$query,$header=null) {
// Entete
$headerini = [
'Accept' => 'application/json',
'Content-Type' => 'application/json',
];
if($header) $header=array_merge($headerini,$header);
else $header=$headerini;
// Paramétrage unirest
\Unirest\Request::verifyPeer(false);
\Unirest\Request::verifyHost(false);
\Unirest\Request::timeout(5);
// Déclaration du proxy
$proxyUse = $this->params->get("proxyUse");
if($proxyUse) {
$proxyHost = $this->params->get("proxyHost");
$proxyPort = $this->params->get("proxyPort");
\Unirest\Request::proxy($proxyHost, $proxyPort, CURLPROXY_HTTP, true);
}
if($query) $query = \Unirest\Request\Body::json($query);
$response = false;
switch($method) {
case "POST":
try{
$response = \Unirest\Request::post($url,$header,$query);
}
catch (\Exception $e) {
die();
return false;
}
break;
case "GET":
try{
$response = @\Unirest\Request::get($url,$header,$query);
}
catch (\Exception $e) {
dump($e);
return false;
}
break;
case "DELETE":
try{
$response = \Unirest\Request::delete($url,$header,$query);
}
catch (\Exception $e) {
return false;
}
break;
case "PATCH":
try{
$response = \Unirest\Request::patch($url,$header,$query);
}
catch (\Exception $e) {
return false;
}
break;
}
return $response;
}
}

155
src/Service/AppSession.php Normal file
View File

@ -0,0 +1,155 @@
<?php
namespace App\Service;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class AppSession {
private $container;
protected $em;
protected $requeststack;
protected $token;
public function __construct(ContainerInterface $container, EntityManagerInterface $em, RequestStack $requeststack, TokenStorageInterface $token)
{
$this->container = $container;
$this->requeststack = $requeststack;
$this->em = $em;
$this->token = $token;
}
public function onDomainParse(RequestEvent $event) {
$session = $this->requeststack->getSession();
$configs = $this->em->getRepository("App\Entity\Config")->findAll();
foreach($configs as $config) {
$session->set($config->getId(), strval($config->getValue()));
}
$session->set("headerimage","uploads/header/".$session->get("headerimage"));
// Calcul couleur
$session->set("colorbgbodylight-darker", $this->adjustBrightness($session->get("colorbgbodylight"),-10));
$session->set("colorfttitlelight-darker", $this->adjustBrightness($session->get("colorfttitlelight"),-50));
$session->set("colorbgbodydark-darker", $this->adjustBrightness($session->get("colorbgbodydark"),-50));
$session->set("colorbgbodydark-lighter", $this->adjustBrightness($session->get("colorbgbodydark"),+50));
$session->set("colorbgbodydark-rgb", $this->hexToRgb($session->get("colorbgbodydark")));
$session->set("colorbgbodydark-darkrgb", $this->hexToRgb($session->get("colorbgbodydark-darker")));
$session->set("colorbgbodydark-lightrgb", $this->hexToRgb($session->get("colorbgbodydark-lighter")));
// Current user
$token = $this->token->getToken();
if(!$token) return;
$curentuser=$token->getUser();
// Préférence par défaut
$session->set("fgheader", true);
// Préférence
if($curentuser!="anon.") {
$preference=$curentuser->getPreference();
if(is_array($preference)) {
// Préférence header
if(array_key_exists("fgheader",$preference)) {
$fgheader=($preference["fgheader"][0]=="true");
$session->set("fgheader", $fgheader);
}
}
}
// Permissions
$showannuaire=false;
$submitgroup=false;
if($curentuser!="anon.") {
switch($session->get("permannu")) {
case "ROLE_USER" :
$showannuaire=($curentuser->hasRole("ROLE_ADMIN")||$curentuser->hasRole("ROLE_MODO")||$curentuser->hasRole("ROLE_MASTER")||$curentuser->hasRole("ROLE_USER"));
break;
case "ROLE_MASTER" :
$showannuaire=($curentuser->hasRole("ROLE_ADMIN")||$curentuser->hasRole("ROLE_MODO")||$curentuser->hasRole("ROLE_MASTER"));
break;
case "ROLE_MODO" :
$showannuaire=($curentuser->hasRole("ROLE_ADMIN")||$curentuser->hasRole("ROLE_MODO"));
break;
}
switch($session->get("permgroup")) {
case "ROLE_USER" :
$submitgroup=($curentuser->hasRole("ROLE_ADMIN")||$curentuser->hasRole("ROLE_MODO")||$curentuser->hasRole("ROLE_MASTER")||$curentuser->hasRole("ROLE_USER"));
break;
case "ROLE_MASTER" :
$submitgroup=($curentuser->hasRole("ROLE_ADMIN")||$curentuser->hasRole("ROLE_MODO")||$curentuser->hasRole("ROLE_MASTER"));
break;
case "ROLE_MODO" :
$submitgroup=($curentuser->hasRole("ROLE_ADMIN")||$curentuser->hasRole("ROLE_MODO"));
break;
}
}
$session->set("showannuaire", $showannuaire);
$session->set("submitgroup", $submitgroup);
// Visite
if($curentuser!="anon.") {
$now=new \DateTime();
if(!$curentuser->getVisitedate()) {
$curentuser->setVisitedate($now);
$curentuser->setVisitecpt($curentuser->getVisitecpt()+1);
$this->em->persist($curentuser);
$this->em->flush();
}
else {
$visitedate=clone $curentuser->getVisitedate();
$visitedate->add(new \DateInterval("PT1H"));
if($visitedate<$now) {
$curentuser->setVisitedate($now);
$curentuser->setVisitecpt($curentuser->getVisitecpt()+1);
$this->em->persist($curentuser);
$this->em->flush();
}
}
}
}
private function adjustBrightness($hex, $steps) {
// Steps should be between -255 and 255. Negative = darker, positive = lighter
$steps = max(-255, min(255, $steps));
// Normalize into a six character long hex string
$hex = str_replace('#', '', $hex);
if (strlen($hex) == 3) {
$hex = str_repeat(substr($hex,0,1), 2).str_repeat(substr($hex,1,1), 2).str_repeat(substr($hex,2,1), 2);
}
// Split into three parts: R, G and B
$color_parts = str_split($hex, 2);
$return = '';
foreach ($color_parts as $color) {
$color = hexdec($color); // Convert to decimal
$color = max(0,min(255,$color + $steps)); // Adjust color
$return .= str_pad(dechex($color), 2, '0', STR_PAD_LEFT); // Make two char hex code
}
return '#'.$return;
}
public function hexToRgb($hex) {
$hex = str_replace('#', '', $hex);
$length = strlen($hex);
$rgb['r'] = hexdec($length == 6 ? substr($hex, 0, 2) : ($length == 3 ? str_repeat(substr($hex, 0, 1), 2) : 0));
$rgb['g'] = hexdec($length == 6 ? substr($hex, 2, 2) : ($length == 3 ? str_repeat(substr($hex, 1, 1), 2) : 0));
$rgb['b'] = hexdec($length == 6 ? substr($hex, 4, 2) : ($length == 3 ? str_repeat(substr($hex, 2, 1), 2) : 0));
return $rgb['r'].",".$rgb['g'].",".$rgb['b'];
}
}

841
src/Service/LdapService.php Normal file
View File

@ -0,0 +1,841 @@
<?php
namespace App\Service;
use Symfony\Component\DependencyInjection\ContainerInterface;
use App\Entity\User;
use App\Entity\Niveau01;
use App\Entity\Niveau02;
use App\Entity\Group;
use App\Entity\UserGroup;
class LdapService
{
private $connection;
public function __construct(ContainerInterface $container)
{
$this->appMasteridentity = $container->getParameter("appMasteridentity");
$this->synchro = $container->getParameter("appSynchro");
$this->host = $container->getParameter("ldapHost");
$this->port = $container->getParameter("ldapPort");
$this->usetls = $container->getParameter("ldapUsetls");
$this->userwriter = $container->getParameter("ldapUserwriter");
$this->user = $container->getParameter("ldapUser");
$this->password = $container->getParameter("ldapPassword");
$this->basedn = $container->getParameter("ldapBasedn");
$this->baseorganisation = $container->getParameter("ldapBaseorganisation");
$this->baseniveau01 = $container->getParameter("ldapBaseniveau01");
$this->baseniveau02 = $container->getParameter("ldapBaseniveau02");
$this->basegroup = $container->getParameter("ldapBasegroup");
$this->baseuser = $container->getParameter("ldapBaseuser");
$this->username = $container->getParameter("ldapUsername");
$this->firstname = $container->getParameter("ldapFirstname");
$this->lastname = $container->getParameter("ldapLastname");
$this->email = $container->getParameter("ldapEmail");
$this->avatar = $container->getParameter("ldapAvatar");
$this->memberof = $container->getParameter("ldapMemberof");
$this->groupgid = $container->getParameter("ldapGroupgid");
$this->groupname = $container->getParameter("ldapGroupname");
$this->groupmember = $container->getParameter("ldapGroupmember");
$this->groupmemberisdn = $container->getParameter("ldapGroupmemberisdn");
$this->filtergroup = $container->getParameter("ldapFiltergroup");
$this->filteruser = $container->getParameter("ldapFilteruser");
$this->userattributes = [$this->username,$this->firstname,$this->lastname,$this->email,$this->avatar,$this->memberof];
}
public function isNine2Ldap() {
return ($this->connect()&&$this->appMasteridentity=="SQL"&&$this->synchro=="NINE2LDAP"&&$this->userwriter&&$this->baseorganisation&&$this->baseniveau01&&$this->baseniveau02&&$this->basegroup&&$this->baseuser);
}
public function connect() {
// Si on est déjà co = on rebind pour gérer le cas d'un timeout de connection
if($this->connection){
if(!@ldap_bind($this->connection, $this->user, $this->password)){
$this->disconnect();
}
}
if($this->connection){
return $this->connection;
} else {
$ldapConn = ldap_connect($this->host, $this->port);
if($ldapConn){
ldap_set_option($ldapConn, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ldapConn, LDAP_OPT_REFERRALS, 0);
if($this->usetls) ldap_start_tls($ldapConn);
if(@ldap_bind( $ldapConn, $this->user, $this->password)){
$this->connection = $ldapConn;
return $this->connection;
}
}
}
return false;
}
public function userconnect($username,$userpassword) {
$ldapConn = ldap_connect($this->host, $this->port);
$this->connection = $ldapConn;
if($this->connection){
ldap_set_option($ldapConn, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ldapConn, LDAP_OPT_REFERRALS, 0);
if($this->usetls) ldap_start_tls($ldapConn);
$dn = $this->getUserDN($username);
if(@ldap_bind( $ldapConn, $dn, $userpassword)){
$res = $this->search(str_replace("*",$username,$this->filteruser),$this->userattributes, $this->baseuser);
$this->disconnect();
return $res;
}
}
$this->disconnect();
return false;
}
public function getParameter($key) {
switch($key) {
case "baseuser" : return $this->baseuser; break;
case "basegroup" : return $this->basegroup; break;
case "baseniveau01" : return $this->baseniveau01; break;
case "baseniveau02" : return $this->baseniveau02; break;
case "basedn" : return $this->basedn; break;
case "filteruser" : return $this->filteruser; break;
}
}
public function search($filter, $attributes = array(), $subBranch = '') {
$connection = $this->connect();
$branch = ($subBranch ? $subBranch : $this->basedn);
$result = ldap_search($connection, $branch, $filter, $attributes,0,0,0);
if(!$result) {
$this->ldapError();
}
return $this->resultToArray($result);
}
public function searchdn($dn, $subBranch = '') {
$connection = $this->connect();
$tbdn=ldap_explode_dn($dn,0);
$branch = ($subBranch ? $subBranch : $this->basedn);
$result = ldap_search($connection, $branch, "(".$tbdn[0].")", [],0,0,0);
if(!$result) {
$this->ldapError();
}
return $this->resultToArray($result);
}
public function deleteByDN($dn){
$connection = $this->connect();
$removed = ldap_delete($connection, $dn);
if(!$removed){
$this->ldapError();
}
}
public function rename($oldDN, $newDN, $parentDN = '', $deleteOldDN = true){
$connection = $this->connect();
$result = ldap_rename($connection, $oldDN, $newDN, $parentDN, $deleteOldDN);
if(!$result) $this->ldapError();
return $result;
}
private function resultToArray($result){
$connection = $this->connect();
$resultArray = array();
if($result){
$entry = ldap_first_entry($connection, $result);
while ($entry){
$row = array();
$attr = ldap_first_attribute($connection, $entry);
while ($attr){
$val = ldap_get_values_len($connection, $entry, $attr);
if(array_key_exists('count', $val) AND $val['count'] == 1){
$row[strtolower($attr)] = $val[0];
} else {
$row[strtolower($attr)] = $val;
}
if(is_array($row[strtolower($attr)])) {
unset($row[strtolower($attr)]["count"]);
}
$attr = ldap_next_attribute($connection, $entry);
}
$resultArray[] = $row;
$entry = ldap_next_entry($connection, $entry);
}
}
return $resultArray;
}
public function in_array_r($item , $array){
return preg_match('/"'.$item.'"/i' , json_encode($array));
}
public function disconnect(){
if($this->connection) {
ldap_unbind($this->connection);
$this->connection=null;
}
}
public function ldapError(){
$connection = $this->connect();
throw new \Exception(
'Error: ('. ldap_errno($connection) .') '. ldap_error($connection)
);
}
public function ldapModify($dn,$attrs) {
$connection = $this->connect();
$result = ldap_modify($connection, $dn, $attrs);
if(!$result) $this->ldapError();
}
//==================================================================================================================================================================
//== Function Organisation==========================================================================================================================================
//==================================================================================================================================================================
public function addOrganisations() {
$ldapentrys=$this->searchdn($this->baseorganisation);
if(empty($ldapentrys)) {
$this->addOrganisation($this->basedn);
}
$ldapentrys=$this->searchdn($this->baseniveau01,$this->baseorganisation);
if(empty($ldapentrys)) {
$this->addOrganisation($this->baseniveau01);
}
$ldapentrys=$this->searchdn($this->baseniveau02,$this->baseorganisation);
if(empty($ldapentrys)) {
$this->addOrganisation($this->baseniveau02);
}
$ldapentrys=$this->searchdn($this->basegroup,$this->baseorganisation);
if(empty($ldapentrys)) {
$this->addOrganisation($this->basegroup);
}
$ldapentrys=$this->searchdn($this->baseuser,$this->baseorganisation);
if(empty($ldapentrys)) {
$this->addOrganisation($this->baseuser);
}
}
public function addOrganisation($dn) {
$connection = $this->connect();
$attrs = array();
$attrs['objectclass'] = ["top","organizationalUnit"];
$result = ldap_add($connection, $dn, $attrs);
if(!$result) $this->ldapError();
return $result;
}
//==================================================================================================================================================================
//== Function User==================================================================================================================================================
//==================================================================================================================================================================
public function addUser(User $user) {
$connection = $this->connect();
$dn = $this->getUserDN($user->getUsername());
$attrs = array();
$attrs['objectclass'] = $this->getObjectClassesUser();
$this->fillAttributesUser($user, $attrs);
foreach($attrs as $key => $value){
if(empty($value)){
unset($attrs[$key]);
}
}
$result = ldap_add($connection, $dn, $attrs);
if(!$result) $this->ldapError();
return $result;
}
public function ismodifyUser(User $user,$entry){
$attrs = [];
$this->fillAttributesUser($user, $attrs);
foreach($attrs as $key => $value) {
if(!array_key_exists($key,$entry)&&!empty($value)) return true;
elseif(array_key_exists($key,$entry)&&$value!=$entry[$key]) return true;
}
foreach($entry as $key => $value) {
if(!array_key_exists($key,$attrs)&&!empty($value)) return true;
elseif(array_key_exists($key,$attrs)&&$value!=$attrs[$key]) return true;
}
return false;
}
public function modifyUser(User $user){
$dn = $this->basedn;
$connection = $this->connect();
$attrs = array();
$this->fillAttributesUser($user, $attrs);
// Rechercher le DN du user
$dn = $this->getUserDN($user->getUsername());
foreach($attrs as $key => $value){
if(empty($value)){
// Bien mettre un @ car si l'attribut est déjà vide cela crache une erreur car l'attribut n'existe déjà plus
@ldap_mod_del($connection, $dn, array($key => array()));
unset($attrs[$key]);
}
}
$result = ldap_modify($connection, $dn, $attrs);
if(!$result) $this->ldapError();
}
public function modifyUserpwd(User $user){
$dn = $this->basedn;
$connection = $this->connect();
$attrs = array();
// Attributs associés au password
if($this->type=="AD")
$attrs["unicodepwd"] = $user->getPasswordad();
$attrs['userpassword'] = $user->getPassword();
// Rechercher le DN du user
$dn = $this->getUserDN($user->getUsername());
foreach($attrs as $key => $value){
if(empty($value)){
// Bien mettre un @ car si l'attribut est déjà vide cela crache une erreur car l'attribut n'existe déjà plus
@ldap_mod_del($connection, $dn, array($key => array()));
unset($attrs[$key]);
}
}
$result = ldap_modify($connection, $dn, $attrs);
if(!$result) $this->ldapError();
}
public function updateNiveauUser(User $user,$todel=false) {
$dn = $this->basedn;
$connection = $this->connect();
// NIVEAU01
// On recherche le Niveau01 actuellement asscocié à l'utilisateur
$criteria = '(&(cn=*)(memberUid='.$user->getUsername().'))';
$subbranch=$this->baseniveau01;
$results = $this->search($criteria, array('cn'), $subbranch);
foreach($results as $result) {
// Si Niveau01 différent de celui en cours on le détache de ce Niveau01
if($result["cn"]!=$user->getNiveau01()->getLabel()||$todel) {
$dn = $this->getNiveau01DN($result["cn"]);
$entry['memberuid'] = $user->getUsername();
$result = ldap_mod_del($connection, $dn, $entry);
if(!$result) $this->ldapError();
}
}
// On recherche le Niveau01 en cours
if(!$todel) {
$criteria = '(cn='.$user->getNiveau01()->getLabel().')';
$subbranch=$this->baseniveau01;
$result = $this->search($criteria, array('memberuid'), $subbranch);
// S'il n'est pas membre du Niveau01 on le rattache
if(!$this->in_array_r($user->getUsername(),$result[0])) {
$dn = $this->getNiveau01DN($user->getNiveau01()->getLabel());
$entry['memberuid'] = $user->getUsername();
$result = ldap_mod_add($connection, $dn, $entry);
if(!$result) $this->ldapError();
}
}
// NIVEAU02
// On recherche le Niveau02 actuellement asscocié à l'utilisateur
$criteria = '(&(cn=*)(memberUid='.$user->getUsername().'))';
$subbranch=$this->baseniveau02;
$results = $this->search($criteria, array('cn'), $subbranch);
foreach($results as $result) {
// Si Niveau02 différent de celui en cours on le détache de ce Niveau02
if($user->getNiveau02()===null||$result["cn"]!=$user->getNiveau02()->getLabel()||$todel) {
$dn = $this->getNiveau02DN($result["cn"]);
$entry['memberuid'] = $user->getUsername();
$result = ldap_mod_del($connection, $dn, $entry);
if(!$result) $this->ldapError();
}
}
// On recherche le Niveau02 en cours
if(!$todel) {
if($user->getNiveau02()!==null) {
$criteria = '(cn='.$user->getNiveau02()->getLabel().')';
$subbranch=$this->baseniveau02;
$result = $this->search($criteria, array('memberuid'), $subbranch);
// S'il n'est pas membre du Niveau02 on le rattache
if(empty($result)||!$this->in_array_r($user->getUsername(),$result[0])) {
$dn = $this->getNiveau02DN($user->getNiveau02()->getLabel());
$entry['memberuid'] = $user->getUsername();
$result = ldap_mod_add($connection, $dn, $entry);
if(!$result) $this->ldapError();
}
}
}
return $result;
}
public function deleteUser(User $user){
$dn = $this->getUserDN($user->getUsername());
return $this->deleteByDN($dn);
}
public function getObjectClassesUser() {
$oc = array(
'top',
'person',
'organizationalPerson',
'inetOrgPerson',
);
return $oc;
}
public function listAttributesUser() {
return [
"uid",
"cn",
"givenname",
"sn",
"mail",
"displayname",
"telephonenumber",
"postaladdress",
"userpassword",
];
}
public function fillAttributesUser(User $user, array &$attrs) {
$attrs['uid'] = $user->getUsername();
$attrs['cn'] = $user->getFirstname() . ' ' . $user->getLastname();
$attrs['givenname'] = $user->getFirstname();
$attrs['sn'] = $user->getLastname();
$attrs['mail'] = $user->getEmail();
$attrs['displayname'] = $user->getFirstname() . ' ' . $user->getLastname();
$attrs['telephonenumber'] = $user->getTelephonenumber();
$attrs['postaladdress'] = $user->getPostaladress();
$attrs['userpassword'] = $user->getPassword();
}
public function getUserDN($username) {
return $this->username.'='.$username.','.$this->baseuser;
}
//==================================================================================================================================================================
//== Function Niveau01==============================================================================================================================================
//==================================================================================================================================================================
public function findNiveau01($ldapfilter) {
$ldapentrys=$this->search($ldapfilter,[$this->groupgid,$this->groupname,$this->groupmember],$this->baseniveau01);
return $ldapentrys;
}
public function findNiveau01ismember($ldapfilter,$username) {
$ldapentrys=$this->findNiveau01($ldapfilter);
foreach($ldapentrys as $ldapentry) {
if(is_array($ldapentry[$this->groupmember])) {
if(in_array($username,$ldapentry[$this->groupmember])) return true;
}
elseif($username==$ldapentry[$this->groupmember]) return true;
}
return false;
}
public function addNiveau01(Niveau01 $niveau01) {
$connection = $this->connect();
$dn = $this->getNiveau01DN($niveau01->getLabel());
$attrs = array();
$attrs['objectclass'] = $this->getObjectClassesNiveau01();
$this->fillAttributesNiveau01($niveau01, $attrs);
foreach($attrs as $key => $value){
if(empty($value)){
unset($attrs[$key]);
}
}
$result = ldap_add($connection, $dn, $attrs);
if(!$result) $this->ldapError();
return $result;
}
public function ismodifyNiveau01(Niveau01 $niveau01,$entry){
$attrs = [];
$this->fillAttributesNiveau01($niveau01, $attrs);
foreach($attrs as $key => $value) {
if(!array_key_exists($key,$entry)&&!empty($value)) return true;
elseif(array_key_exists($key,$entry)&&$value!=$entry[$key]) return true;
}
foreach($entry as $key => $value) {
if(!array_key_exists($key,$attrs)&&!empty($value)) return true;
elseif(array_key_exists($key,$attrs)&&$value!=$attrs[$key]) return true;
}
return false;
}
public function modifyNiveau01(Niveau01 $niveau01,$oldid){
$dn = $this->basedn;
$connection = $this->connect();
$attrs = array();
$this->fillAttributesNiveau01($niveau01, $attrs);
unset($attrs["cn"]);
$dn = $this->getNiveau01DN($niveau01->getLabel());
foreach($attrs as $key => $value){
if(empty($value)){
// Bien mettre un @ car si l'attribut est déjà vide cela crache une erreur car l'attribut n'existe déjà plus
@ldap_mod_del($connection, $dn, array($key => array()));
unset($attrs[$key]);
}
}
if(isset($oldid)&&$oldid!=$niveau01->getLabel()) {
$olddn = $this->getNiveau01DN($oldid);
$this->rename($olddn,"cn=".$niveau01->getLabel(),$this->baseniveau01);
}
$result = ldap_modify($connection, $dn, $attrs);
if(!$result) $this->ldapError();
}
public function deleteNiveau01(Niveau01 $niveau01){
$dn = $this->getNiveau01DN($niveau01->getLabel());
return $this->deleteByDN($dn);
}
private function getObjectClassesNiveau01() {
$oc = array(
'top',
'posixGroup',
);
return $oc;
}
public function listAttributesNiveau01() {
return [
"cn",
"gidnumber",
"memberuid",
];
}
public function fillAttributesNiveau01(Niveau01 $niveau01, array &$attrs) {
$attrs['cn'] = $niveau01->getLabel();
$attrs['gidnumber'] = $niveau01->getId();
$attrs['memberuid'] = [];
foreach($niveau01->getUsers() as $user) {
array_push($attrs['memberuid'],$user->getUsername());
}
sort($attrs['memberuid']);
if(count($attrs['memberuid'])==1) $attrs['memberuid'] = $attrs['memberuid'][0];
}
public function getNiveau01DN($id) {
return 'cn='.$id.','.$this->baseniveau01;
}
//==================================================================================================================================================================
//== Function Niveau02==============================================================================================================================================
//==================================================================================================================================================================
public function addNiveau02(Niveau02 $niveau02) {
$connection = $this->connect();
$dn = $this->getNiveau02DN($niveau02->getLabel());
$attrs = array();
$attrs['objectclass'] = $this->getObjectClassesNiveau02();
$this->fillAttributesNiveau02($niveau02, $attrs);
foreach($attrs as $key => $value){
if(empty($value)){
unset($attrs[$key]);
}
}
$result = ldap_add($connection, $dn, $attrs);
if(!$result) $this->ldapError();
return $result;
}
public function ismodifyNiveau02(Niveau02 $niveau02,$entry){
$attrs = [];
$this->fillAttributesNiveau02($niveau02, $attrs);
foreach($attrs as $key => $value) {
if(!array_key_exists($key,$entry)&&!empty($value)) return true;
elseif(array_key_exists($key,$entry)&&$value!=$entry[$key]) return true;
}
foreach($entry as $key => $value) {
if(!array_key_exists($key,$attrs)&&!empty($value)) return true;
elseif(array_key_exists($key,$attrs)&&$value!=$attrs[$key]) return true;
}
return false;
}
public function modifyNiveau02(Niveau02 $niveau02,$oldid){
$dn = $this->basedn;
$connection = $this->connect();
$attrs = array();
$this->fillAttributesNiveau02($niveau02, $attrs);
unset($attrs["cn"]);
$dn = $this->getNiveau02DN($niveau02->getLabel());
foreach($attrs as $key => $value){
if(empty($value)){
// Bien mettre un @ car si l'attribut est déjà vide cela crache une erreur car l'attribut n'existe déjà plus
@ldap_mod_del($connection, $dn, array($key => array()));
unset($attrs[$key]);
}
}
if(isset($oldid)&&$oldid!=$niveau02->getLabel()) {
$olddn = $this->getNiveau02DN($oldid);
$this->rename($olddn,"cn=".$niveau02->getLabel(),$this->baseniveau02);
}
$result = ldap_modify($connection, $dn, $attrs);
if(!$result) $this->ldapError();
}
public function deleteNiveau02(Niveau02 $niveau02){
$dn = $this->getNiveau02DN($niveau02->getLabel());
return $this->deleteByDN($dn);
}
private function getObjectClassesNiveau02() {
$oc = array(
'top',
'posixGroup',
);
return $oc;
}
public function listAttributesNiveau02() {
return [
"cn",
"gidnumber",
"memberuid"
];
}
public function fillAttributesNiveau02(Niveau02 $niveau02, array &$attrs) {
$attrs['cn'] = $niveau02->getLabel();
$attrs['gidnumber'] = $niveau02->getId();
$attrs['memberuid'] = [];
foreach($niveau02->getUsers() as $user) {
array_push($attrs['memberuid'],$user->getUsername());
}
sort($attrs['memberuid']);
if(count($attrs['memberuid'])==1) $attrs['memberuid'] = $attrs['memberuid'][0];
}
public function getNiveau02DN($id) {
return 'cn='.$id.','.$this->baseniveau02;
}
//==================================================================================================================================================================
//== Function Group=================================================================================================================================================
//==================================================================================================================================================================
public function addGroup(Group $group) {
$connection = $this->connect();
$dn = $this->getGroupDN($group->getLabel());
$attrs = array();
$attrs['objectclass'] = $this->getObjectClassesGroup();
$this->fillAttributesGroup($group, $attrs);
foreach($attrs as $key => $value){
if(empty($value)){
unset($attrs[$key]);
}
}
$result = ldap_add($connection, $dn, $attrs);
if(!$result) $this->ldapError();
return $result;
}
public function ismodifyGroup(Group $group,$entry){
$attrs = [];
$this->fillAttributesGroup($group, $attrs);
foreach($attrs as $key => $value) {
if(!array_key_exists($key,$entry)&&!empty($value)) return true;
elseif(array_key_exists($key,$entry)&&$value!=$entry[$key]) return true;
}
foreach($entry as $key => $value) {
if(!array_key_exists($key,$attrs)&&!empty($value)) return true;
elseif(array_key_exists($key,$attrs)&&$value!=$attrs[$key]) return true;
}
return false;
}
public function modifyGroup(Group $group,$oldid){
$dn = $this->basedn;
$connection = $this->connect();
$attrs = array();
$this->fillAttributesGroup($group, $attrs);
unset($attrs["cn"]);
$dn = $this->getGroupDN($group->getLabel());
foreach($attrs as $key => $value){
if(empty($value)){
// Bien mettre un @ car si l'attribut est déjà vide cela crache une erreur car l'attribut n'existe déjà plus
@ldap_mod_del($connection, $dn, array($key => array()));
unset($attrs[$key]);
}
}
if(isset($oldid)&&$oldid!=$group->getLabel()) {
$olddn = $this->getGroupDN($oldid);
$this->rename($olddn,"cn=".$group->getLabel(),$this->basegroup);
}
$result = ldap_modify($connection, $dn, $attrs);
if(!$result) $this->ldapError();
}
public function deleteGroup(Group $group){
$dn = $this->getGroupDN($group->getLabel());
return $this->deleteByDN($dn);
}
private function getObjectClassesGroup() {
$oc = array(
'top',
'posixGroup',
);
return $oc;
}
public function listAttributesGroup() {
return [
"cn",
"gidnumber",
"memberuid"
];
}
public function fillAttributesGroup(Group $group, array &$attrs) {
$attrs['cn'] = $group->getLabel();
$attrs['gidnumber'] = $group->getId();
$attrs['memberuid'] = [];
foreach($group->getUsers() as $usergroup) {
array_push($attrs['memberuid'],$usergroup->getUser()->getUsername());
}
sort($attrs['memberuid']);
if(count($attrs['memberuid'])==1) $attrs['memberuid'] = $attrs['memberuid'][0];
}
public function getGroupDN($id) {
return 'cn='.$id.','.$this->basegroup;
}
//==================================================================================================================================================================
//== Function UserGroup=============================================================================================================================================
//==================================================================================================================================================================
function addUserGroup(UserGroup $usergroup) {
$dn = $this->basedn;
$connection = $this->connect();
// On recherche le group en cours
$criteria = '(cn='.$usergroup->getGroup()->getLabel().')';
$subbranch=$this->basegroup;
$result = $this->search($criteria, array('memberuid'), $subbranch);
if(!$this->in_array_r($usergroup->getUser()->getUsername(),$result[0])) {
$dn = $this->getGroupDN($usergroup->getGroup()->getLabel());
$entry['memberuid'] = $usergroup->getUser()->getUsername();
$result = ldap_mod_add($connection, $dn, $entry);
if(!$result) $this->ldapError();
}
return $result;
}
function delUserGroup(UserGroup $usergroup) {
$dn = $this->basedn;
$connection = $this->connect();
// On recherche le group en cours
$criteria = '(cn='.$usergroup->getGroup()->getLabel().')';
$subbranch=$this->basegroup;
$result = $this->search($criteria, array('memberuid'), $subbranch);
if($this->in_array_r($usergroup->getUser()->getUsername(),$result[0])) {
$dn = $this->getGroupDN($usergroup->getGroup()->getLabel());
$entry['memberuid'] = $usergroup->getUser()->getUsername();
$result = ldap_mod_del($connection, $dn, $entry);
if(!$result) $this->ldapError();
}
return $result;
}
}

View File

@ -0,0 +1,57 @@
<?php
namespace App\Service;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Email;
use Symfony\Component\Mime\Address;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
class MailService
{
protected $mailer;
protected $twig;
public function __construct(MailerInterface $mailer, \Twig\Environment $twig)
{
$this->mailer = $mailer;
$this->twig = $twig;
}
/**
* Send email
*
* @param string $template email template
* @param mixed $parameters custom params for template
* @param string $to to email address or array of email addresses
* @param string $from from email address
* @param string $fromName from name
*
* @return boolean send status
*/
public function sendEmail($subject, $body, $to, $from, $fromName = null)
{
$template = $this->twig->load('Home/mail.html.twig');
$parameters=["subject"=>$subject,"body"=>$body];
$subject = $template->renderBlock('subject', $parameters);
$bodyHtml = $template->renderBlock('body', $parameters);
try {
if(!is_array($to)) $to=[$to];
foreach($to as $t) {
$message = (new Email())
->subject($subject)
->from(Address::create($fromName. "<".$from.">"))
->to($t)
->html($bodyHtml);
$this->mailer->send($message);
}
} catch (TransportExceptionInterface $e) {
return $e->getMessage();
}
return true;
}
}

View File

@ -0,0 +1,36 @@
<?php
namespace App\Service;
use Symfony\Component\PasswordHasher\Exception\InvalidPasswordException;
use Symfony\Component\PasswordHasher\Hasher\CheckPasswordLengthTrait;
use Symfony\Component\PasswordHasher\LegacyPasswordHasherInterface;
class PasswordEncoder implements LegacyPasswordHasherInterface
{
use CheckPasswordLengthTrait;
public function hash(string $plainPassword, string $salt = null): string
{
if ($this->isPasswordTooLong($plainPassword)) {
throw new InvalidPasswordException();
}
$hash = "{SSHA}" . base64_encode(pack("H*", sha1($plainPassword . $salt)) . $salt);
return $hash;
}
public function verify(string $hashedPassword, string $plainPassword, string $salt = null): bool
{
if ('' === $plainPassword || $this->isPasswordTooLong($plainPassword)) {
return false;
}
var_dump($salt);
return $this->hash($plainPassword,$salt) === $hashedPassword;
}
public function needsRehash(string $hashedPassword): bool
{
return false;
}
}

View File

@ -0,0 +1,87 @@
<?php
namespace App\Service;
use Doctrine\ORM\EntityManagerInterface;
use Oneup\UploaderBundle\Event\PostPersistEvent;
class UploadListener
{
private $em;
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
protected function getHeight($image) {
$size = getimagesize($image);
$height = $size[1];
return $height;
}
// Cacul de la largeur
protected function getWidth($image) {
$size = getimagesize($image);
$width = $size[0];
return $width;
}
protected function resizeImage($image,$width,$height,$scale) {
list($imagewidth, $imageheight, $imageType) = getimagesize($image);
$imageType = image_type_to_mime_type($imageType);
$newImageWidth = ceil($width * $scale);
$newImageHeight = ceil($height * $scale);
$newImage = imagecreatetruecolor($newImageWidth,$newImageHeight);
switch($imageType) {
case "image/gif":
$source=imagecreatefromgif($image);
break;
case "image/pjpeg":
case "image/jpeg":
case "image/jpg":
$source=imagecreatefromjpeg($image);
break;
case "image/png":
case "image/x-png":
$source=imagecreatefrompng($image);
break;
}
$newImage = imagecreatetruecolor( $newImageWidth, $newImageHeight );
imagealphablending( $newImage, false );
imagesavealpha( $newImage, true );
imagecopyresampled($newImage,$source,0,0,0,0,$newImageWidth,$newImageHeight,$width,$height);
switch($imageType) {
case "image/gif":
imagegif($newImage,$image);
break;
case "image/pjpeg":
case "image/jpeg":
case "image/jpg":
imagejpeg($newImage,$image,90);
break;
case "image/png":
case "image/x-png":
imagepng($newImage,$image);
break;
}
chmod($image, 0640);
return $image;
}
public function onUpload(PostPersistEvent $event)
{
$type=$event->getType();
switch($type) {
default:
$file=$event->getFile();
$filename=$file->getFilename();
$response = $event->getResponse();
$response['file'] = $filename;
break;
}
}
}

31
src/Twig/AppExtension.php Normal file
View File

@ -0,0 +1,31 @@
<?php
namespace App\Twig;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
class AppExtension extends AbstractExtension
{
protected $container;
public function getFilters()
{
return [
new TwigFilter('urlavatar', [$this, 'urlavatar']),
];
}
public function urlavatar($avatar)
{
if(stripos($avatar,"http")===0)
return $avatar;
else
return $this->container->getParameter("appAlias")."uploads/avatar/".$avatar;
}
public function setContainer($container)
{
$this->container = $container;
}
}

View File

@ -0,0 +1,12 @@
<?php
namespace App\Validator;
use Symfony\Component\Validator\Constraint;
/**
* @Annotation
*/
class Grouplabel extends Constraint
{
public $message = "Caractères interdit dans ce label";
}

View File

@ -0,0 +1,29 @@
<?php
namespace App\Validator;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
/**
* @Annotation
*/
class GrouplabelValidator extends ConstraintValidator
{
public function validate($value, Constraint $constraint)
{
/*
$tmp=$this->getEntityBy("App:Group","label",$value);
if($tmp) $form->addError(new FormError('Un groupe utilise déjà ce label'));
$tmp=$this->getEntityBy("App:Niveau02","label",$data->getLabel());
if($tmp) $form->addError(new FormError('Un niveau de rang 02 utilise déjà ce label'));
*/
// On s'assure que le label ne contient pas des caractères speciaux
$string = preg_replace('~[^ éèêôöàïî\'@a-zA-Z0-9._-]~', '', $value);
if($string!=$value)
{
$this->context->addViolation($constraint->message);
}
}
}

View File

@ -0,0 +1,13 @@
<?php
namespace App\Validator;
use Symfony\Component\Validator\Constraint;
/**
* @Annotation
*/
class Niveau01unique extends Constraint
{
public $messagegroup = "Un groupe utilise déjà ce label";
public $messageniveau02 = "Un niveau de rang 02 utilise déjà ce label";
}

View File

@ -0,0 +1,32 @@
<?php
namespace App\Validator;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Doctrine\ORM\EntityManagerInterface;
/**
* @Annotation
*/
class Niveau01uniqueValidator extends ConstraintValidator
{
protected $em;
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
public function validate($value, Constraint $constraint)
{
$group = $this->em->getRepository("App\Entity\Group")->findOneBy(["label"=>$value]);
if($group) {
$this->context->addViolation($constraint->messagegroup);
}
$niveau02 = $this->em->getRepository("App\Entity\Niveau02")->findOneBy(["label"=>$value]);
if($niveau02) {
$this->context->addViolation($constraint->messageniveau02);
}
}
}

View File

@ -0,0 +1,13 @@
<?php
namespace App\Validator;
use Symfony\Component\Validator\Constraint;
/**
* @Annotation
*/
class Niveau02unique extends Constraint
{
public $messagegroup = "Un groupe utilise déjà ce label";
public $messageniveau01 = "Un niveau de rang 01 utilise déjà ce label";
}

View File

@ -0,0 +1,32 @@
<?php
namespace App\Validator;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Doctrine\ORM\EntityManagerInterface;
/**
* @Annotation
*/
class Niveau02uniqueValidator extends ConstraintValidator
{
protected $em;
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
public function validate($value, Constraint $constraint)
{
$group = $this->em->getRepository("App\Entity\Group")->findOneBy(["label"=>$value]);
if($group) {
$this->context->addViolation($constraint->messagegroup);
}
$niveau02 = $this->em->getRepository("App\Entity\Niveau01")->findOneBy(["label"=>$value]);
if($niveau02) {
$this->context->addViolation($constraint->messageniveau01);
}
}
}

View File

@ -0,0 +1,12 @@
<?php
namespace App\Validator;
use Symfony\Component\Validator\Constraint;
/**
* @Annotation
*/
class Password extends Constraint
{
public $message = "Votre mot de passe doit contenir au minimum 8 caractères, constitué de chiffres, de lettres et caractères spéciaux";
}

View File

@ -0,0 +1,29 @@
<?php
namespace App\Validator;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
/**
* @Annotation
*/
class PasswordValidator extends ConstraintValidator
{
public function validate($value, Constraint $constraint)
{
if(!empty($value)) {
if (strlen($value) < '8') {
$this->context->addViolation($constraint->message);
}
elseif(!preg_match("#[0-9]+#",$value)) {
$this->context->addViolation($constraint->message);
}
elseif(!preg_match("#[a-zA-Z]+#",$value)) {
$this->context->addViolation($constraint->message);
}
elseif(!preg_match("/[|!@#$%&*\/=?,;.:\-_+~^\\\]/",$value)) {
$this->context->addViolation($constraint->message);
}
}
}
}

View File

@ -0,0 +1,13 @@
<?php
namespace App\Validator;
use Symfony\Component\Validator\Constraint;
/**
* @Annotation
*/
class Userusername extends Constraint
{
public $messageinvalid = "Le login n'est pas valide";
public $messagenotunique = "Le login exisite déjà";
}

View File

@ -0,0 +1,41 @@
<?php
namespace App\Validator;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Doctrine\ORM\EntityManagerInterface;
/**
* @Annotation
*/
class UserusernameValidator extends ConstraintValidator
{
protected $em;
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
public function validate($value, Constraint $constraint)
{
if(!empty($value)) {
// On s'assure que le login soit de 5 caractères minimum
if (strlen($value) < '5') {
$this->context->addViolation($constraint->messageinvalid);
}
// On s'assure que le username ne contient pas des caractères speciaux
$string = preg_replace('~[^@a-zA-Z0-9._-]~', '', $value);
if($string!=$value)
$this->context->addViolation($constraint->messageinvalid);
// On s'assure que le username n'existe pas dans la table des registration
$registration = $this->em->getRepository("App\Entity\Registration")->findOneBy(["username"=>$value]);
if($registration) {
$this->context->addViolation($constraint->messagenotunique);
}
}
}
}