fix(continuous-integration): correction php-cs-fixer
Cadoles/nineskeletor/pipeline/pr-master This commit looks good Details

This commit is contained in:
Arnaud Fornerot 2022-09-23 16:14:15 +02:00
parent 5f3cc51f5c
commit b78f54b76c
70 changed files with 5943 additions and 5549 deletions

View File

@ -1,16 +1,13 @@
<?php <?php
namespace App\Command; namespace App\Command;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\DependencyInjection\ContainerInterface;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Finder\Finder;
use App\Entity\Tallyday as Tallyday;
class CleanRegistrationCommand extends Command class CleanRegistrationCommand extends Command
{ {
@ -41,7 +38,7 @@ class CleanRegistrationCommand extends Command
{ {
$this->output = $output; $this->output = $output;
$this->filesystem = new Filesystem(); $this->filesystem = new Filesystem();
$this->rootlog = $this->container->get('kernel')->getLogDir()."/"; $this->rootlog = $this->container->get('kernel')->getLogDir().'/';
$this->writelnred(''); $this->writelnred('');
$this->writelnred('== app:CleanRegistration'); $this->writelnred('== app:CleanRegistration');
@ -53,27 +50,35 @@ class CleanRegistrationCommand extends Command
->select('table') ->select('table')
->from('App\Entity\Registration', 'table') ->from('App\Entity\Registration', 'table')
->where('table.keyexpire<:now') ->where('table.keyexpire<:now')
->setParameter("now",$now->format("Y-m-d H:i:s")) ->setParameter('now', $now->format('Y-m-d H:i:s'))
->getQuery() ->getQuery()
->getResult(); ->getResult();
foreach ($datas as $data) { foreach ($datas as $data) {
$this->writeln('Inscription supprimée = '.$data->getkeyexpire()->format("Y-m-d H:i:s")." >> ".$data->getUsername()); $this->writeln('Inscription supprimée = '.$data->getkeyexpire()->format('Y-m-d H:i:s').' >> '.$data->getUsername());
$this->em->remove($data); $this->em->remove($data);
$this->em->flush(); $this->em->flush();
} }
$this->writeln(''); $this->writeln('');
return Command::SUCCESS; return Command::SUCCESS;
} }
private function writelnred($string) { private function writelnred($string)
{
$this->output->writeln('<fg=red>'.$string.'</>'); $this->output->writeln('<fg=red>'.$string.'</>');
$this->filesystem->appendToFile($this->rootlog.'cron.log', $string."\n"); $this->filesystem->appendToFile($this->rootlog.'cron.log', $string."\n");
if($this->byexec) $this->filesystem->appendToFile($this->rootlog.'exec.log', $string."\n"); if ($this->byexec) {
$this->filesystem->appendToFile($this->rootlog.'exec.log', $string."\n");
} }
private function writeln($string) { }
private function writeln($string)
{
$this->output->writeln($string); $this->output->writeln($string);
$this->filesystem->appendToFile($this->rootlog.'cron.log', $string."\n"); $this->filesystem->appendToFile($this->rootlog.'cron.log', $string."\n");
if($this->byexec) $this->filesystem->appendToFile($this->rootlog.'exec.log', $string."\n"); if ($this->byexec) {
$this->filesystem->appendToFile($this->rootlog.'exec.log', $string."\n");
}
} }
} }

View File

@ -2,26 +2,24 @@
namespace App\Command; namespace App\Command;
use App\Entity\Cron;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Command\LockableTrait;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\DependencyInjection\ContainerInterface;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Filesystem\Filesystem; 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 class CronCommand extends Command
{ {
use LockableTrait;
private $container; private $container;
private $em; private $em;
private $output; private $output;
private $filesystem; private $filesystem;
private $rootlog; private $rootlog;
use LockableTrait;
public function __construct(ContainerInterface $container, EntityManagerInterface $em) public function __construct(ContainerInterface $container, EntityManagerInterface $em)
{ {
@ -42,10 +40,11 @@ class CronCommand extends Command
{ {
$this->output = $output; $this->output = $output;
$this->filesystem = new Filesystem(); $this->filesystem = new Filesystem();
$this->rootlog = $this->container->get('kernel')->getLogDir()."/"; $this->rootlog = $this->container->get('kernel')->getLogDir().'/';
if (!$this->lock()) { if (!$this->lock()) {
$this->output->writeln("CRON LOCK"); $this->output->writeln('CRON LOCK');
return Command::FAILURE; return Command::FAILURE;
} }
@ -61,7 +60,7 @@ class CronCommand extends Command
$this->writelnred('== CRON =================================================================================================='); $this->writelnred('== CRON ==================================================================================================');
$this->writelnred('=========================================================================================================='); $this->writelnred('==========================================================================================================');
$this->writeln('Date = '.$now->format('Y-m-d H:i:s')); $this->writeln('Date = '.$now->format('Y-m-d H:i:s'));
$this->writeln ('Application = '.$this->container->getParameter("appName")); $this->writeln('Application = '.$this->container->getParameter('appName'));
} }
foreach ($crons as $cron) { foreach ($crons as $cron) {
@ -81,15 +80,16 @@ class CronCommand extends Command
$jsonparameter = json_decode($cron->getJsonargument(), true); $jsonparameter = json_decode($cron->getJsonargument(), true);
// Formater la chaine de parametre // Formater la chaine de parametre
if(!$jsonparameter) $jsonparameter=[]; if (!$jsonparameter) {
$jsonparameter = [];
}
$parameter = new ArrayInput($jsonparameter); $parameter = new ArrayInput($jsonparameter);
// Executer la commande // Executer la commande
try { try {
$returnCode = $command->run($parameter, $output); $returnCode = $command->run($parameter, $output);
} } catch (\Exception $e) {
catch(\Exception $e) { $this->writelnred('JOB EN ERREUR .'.$e->getMessage());
$this->writelnred("JOB EN ERREUR .".$e->getMessage());
$returnCode = Command::FAILURE; $returnCode = Command::FAILURE;
} }
@ -98,34 +98,38 @@ class CronCommand extends Command
$cron->setEndexecdate($now); $cron->setEndexecdate($now);
// Si interval par heure // Si interval par heure
if(fmod($cron->getRepeatinterval(),3600)==0) if (0 == fmod($cron->getRepeatinterval(), 3600)) {
$next = clone $cron->getNextexecdate(); $next = clone $cron->getNextexecdate();
else } else {
$next = new \DateTime(); $next = new \DateTime();
}
$next->add(new \DateInterval('PT'.$cron->getRepeatinterval().'S')); $next->add(new \DateInterval('PT'.$cron->getRepeatinterval().'S'));
$cron->setNextexecdate($next); $cron->setNextexecdate($next);
// Statut OK/KO // Statut OK/KO
$cron->setStatut(($returnCode==Command::FAILURE?0:1)); $cron->setStatut(Command::FAILURE == $returnCode ? 0 : 1);
$this->em->flush(); $this->em->flush();
} }
if ($crons) { if ($crons) {
$this->writelnred("=="); $this->writelnred('==');
$this->writelnred("FIN CRON"); $this->writelnred('FIN CRON');
$this->writelnred("=="); $this->writelnred('==');
$this->writelnred(""); $this->writelnred('');
} }
return Command::SUCCESS; return Command::SUCCESS;
} }
private function writelnred($string) { private function writelnred($string)
{
$this->output->writeln('<fg=red>'.$string.'</>'); $this->output->writeln('<fg=red>'.$string.'</>');
$this->filesystem->appendToFile($this->rootlog.'cron.log', $string."\n"); $this->filesystem->appendToFile($this->rootlog.'cron.log', $string."\n");
} }
private function writeln($string) {
private function writeln($string)
{
$this->output->writeln($string); $this->output->writeln($string);
$this->filesystem->appendToFile($this->rootlog.'cron.log', $string."\n"); $this->filesystem->appendToFile($this->rootlog.'cron.log', $string."\n");
} }

View File

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

View File

@ -1,17 +1,15 @@
<?php <?php
namespace App\Command; namespace App\Command;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\DependencyInjection\ContainerInterface;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\Filesystem\Filesystem;
use Cadoles\CoreBundle\Entity\User;
class SetPasswordCommand extends Command class SetPasswordCommand extends Command
{ {
private $container; private $container;
@ -42,9 +40,7 @@ class SetPasswordCommand extends Command
{ {
$this->output = $output; $this->output = $output;
$this->filesystem = new Filesystem(); $this->filesystem = new Filesystem();
$this->rootlog = $this->container->get('kernel')->getLogDir()."/"; $this->rootlog = $this->container->get('kernel')->getLogDir().'/';
$this->writelnred(''); $this->writelnred('');
$this->writelnred('== app:SetPasword'); $this->writelnred('== app:SetPasword');
@ -56,7 +52,7 @@ class SetPasswordCommand extends Command
$password = $input->getArgument('password'); $password = $input->getArgument('password');
$this->writeln($password); $this->writeln($password);
$user = $this->em->getRepository('App\Entity\User')->findOneBy(array('username' => $username)); $user = $this->em->getRepository('App\Entity\User')->findOneBy(['username' => $username]);
if ($user) { if ($user) {
// Set Password // Set Password
$user->setPassword($password); $user->setPassword($password);
@ -65,19 +61,22 @@ class SetPasswordCommand extends Command
} }
$this->writeln(''); $this->writeln('');
return Command::SUCCESS; return Command::SUCCESS;
} }
private function writelnred($string) { private function writelnred($string)
{
$this->output->writeln('<fg=red>'.$string.'</>'); $this->output->writeln('<fg=red>'.$string.'</>');
$this->filesystem->appendToFile($this->rootlog.'cron.log', $string."\n"); $this->filesystem->appendToFile($this->rootlog.'cron.log', $string."\n");
} }
private function writeln($string) {
if(!$string) $string=" "; private function writeln($string)
{
if (!$string) {
$string = ' ';
}
$this->output->writeln($string); $this->output->writeln($string);
$this->filesystem->appendToFile($this->rootlog.'cron.log', $string."\n"); $this->filesystem->appendToFile($this->rootlog.'cron.log', $string."\n");
} }
} }

View File

@ -1,25 +1,20 @@
<?php <?php
namespace App\Command; 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\Group;
use App\Entity\Niveau01;
use App\Entity\User;
use App\Entity\UserGroup; use App\Entity\UserGroup;
use App\Service\ApiService;
use App\Service\LdapService;
use Doctrine\ORM\EntityManagerInterface;
use Ramsey\Uuid\Uuid;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Filesystem\Filesystem;
class SynchroCommand extends Command class SynchroCommand extends Command
{ {
@ -83,54 +78,52 @@ class SynchroCommand extends Command
{ {
$this->output = $output; $this->output = $output;
$this->filesystem = new Filesystem(); $this->filesystem = new Filesystem();
$this->rootlog = $this->container->get('kernel')->getLogDir()."/"; $this->rootlog = $this->container->get('kernel')->getLogDir().'/';
$this->appMasteridentity = $this->container->getParameter('appMasteridentity'); $this->appMasteridentity = $this->container->getParameter('appMasteridentity');
$appSynchro = $this->container->getParameter('appSynchro'); $appSynchro = $this->container->getParameter('appSynchro');
$this->synchro = $this->container->getParameter("appSynchro"); $this->synchro = $this->container->getParameter('appSynchro');
$this->synchropurgeniveau01 = $this->container->getParameter("appSynchroPurgeNiveau01"); $this->synchropurgeniveau01 = $this->container->getParameter('appSynchroPurgeNiveau01');
$this->synchropurgeniveau02 = $this->container->getParameter("appSynchroPurgeNiveau02"); $this->synchropurgeniveau02 = $this->container->getParameter('appSynchroPurgeNiveau02');
$this->synchropurgegroup = $this->container->getParameter("appSynchroPurgeGroup"); $this->synchropurgegroup = $this->container->getParameter('appSynchroPurgeGroup');
$this->synchropurgeuser = $this->container->getParameter("appSynchroPurgeUser"); $this->synchropurgeuser = $this->container->getParameter('appSynchroPurgeUser');
$this->host = $this->container->getParameter("ldapHost"); $this->host = $this->container->getParameter('ldapHost');
$this->port = $this->container->getParameter("ldapPort"); $this->port = $this->container->getParameter('ldapPort');
$this->usetls = $this->container->getParameter("ldapUsetls"); $this->usetls = $this->container->getParameter('ldapUsetls');
$this->userwriter = $this->container->getParameter("ldapUserwriter"); $this->userwriter = $this->container->getParameter('ldapUserwriter');
$this->user = $this->container->getParameter("ldapUser"); $this->user = $this->container->getParameter('ldapUser');
$this->password = $this->container->getParameter("ldapPassword"); $this->password = $this->container->getParameter('ldapPassword');
$this->basedn = $this->container->getParameter("ldapBasedn"); $this->basedn = $this->container->getParameter('ldapBasedn');
$this->baseorganisation = $this->container->getParameter("ldapBaseorganisation"); $this->baseorganisation = $this->container->getParameter('ldapBaseorganisation');
$this->baseniveau01 = $this->container->getParameter("ldapBaseniveau01"); $this->baseniveau01 = $this->container->getParameter('ldapBaseniveau01');
$this->baseniveau02 = $this->container->getParameter("ldapBaseniveau02"); $this->baseniveau02 = $this->container->getParameter('ldapBaseniveau02');
$this->basegroup = $this->container->getParameter("ldapBasegroup"); $this->basegroup = $this->container->getParameter('ldapBasegroup');
$this->baseuser = $this->container->getParameter("ldapBaseuser"); $this->baseuser = $this->container->getParameter('ldapBaseuser');
$this->username = $this->container->getParameter("ldapUsername"); $this->username = $this->container->getParameter('ldapUsername');
$this->firstname = $this->container->getParameter("ldapFirstname"); $this->firstname = $this->container->getParameter('ldapFirstname');
$this->lastname = $this->container->getParameter("ldapLastname"); $this->lastname = $this->container->getParameter('ldapLastname');
$this->email = $this->container->getParameter("ldapEmail"); $this->email = $this->container->getParameter('ldapEmail');
$this->avatar = $this->container->getParameter("ldapAvatar"); $this->avatar = $this->container->getParameter('ldapAvatar');
$this->memberof = $this->container->getParameter("ldapMemberof"); $this->memberof = $this->container->getParameter('ldapMemberof');
$this->groupgid = $this->container->getParameter("ldapGroupgid"); $this->groupgid = $this->container->getParameter('ldapGroupgid');
$this->groupname = $this->container->getParameter("ldapGroupname"); $this->groupname = $this->container->getParameter('ldapGroupname');
$this->groupmember = $this->container->getParameter("ldapGroupmember"); $this->groupmember = $this->container->getParameter('ldapGroupmember');
$this->groupmemberisdn = $this->container->getParameter("ldapGroupmemberisdn"); $this->groupmemberisdn = $this->container->getParameter('ldapGroupmemberisdn');
$this->filtergroup = $this->container->getParameter("ldapFiltergroup"); $this->filtergroup = $this->container->getParameter('ldapFiltergroup');
$this->filteruser = $this->container->getParameter("ldapFilteruser"); $this->filteruser = $this->container->getParameter('ldapFilteruser');
switch ($appSynchro) { switch ($appSynchro) {
case "LDAP2NINE": case 'LDAP2NINE':
$return = $this->ldap2nine(); $return = $this->ldap2nine();
break; break;
case "NINE2LDAP": case 'NINE2LDAP':
$return = $this->nine2ldap(); $return = $this->nine2ldap();
break; break;
case "NINE2NINE": case 'NINE2NINE':
$return = $this->nine2nine(); $return = $this->nine2nine();
break; break;
@ -140,26 +133,27 @@ class SynchroCommand extends Command
} }
$this->writeln(''); $this->writeln('');
return $return; return $return;
} }
private function ldap2nine() private function ldap2nine()
{ {
$this->writelnred(''); $this->writelnred('');
$this->writelnred('== app:Synchro'); $this->writelnred('== app:Synchro');
$this->writelnred('=========================================================================================================='); $this->writelnred('==========================================================================================================');
// Synchronisation ldap2nine possible uniquement si appMasteridentity=LDAP or SSO // Synchronisation ldap2nine possible uniquement si appMasteridentity=LDAP or SSO
if($this->appMasteridentity!="LDAP"&&$this->appMasteridentity!="SSO") { if ('LDAP' != $this->appMasteridentity && 'SSO' != $this->appMasteridentity) {
$this->writeln("Synchronisation impossible si appMasteridentity!=LDAP et appMasteridentity!=SSO"); $this->writeln('Synchronisation impossible si appMasteridentity!=LDAP et appMasteridentity!=SSO');
return Command::FAILURE; return Command::FAILURE;
} }
// Synchronisation impossible si aucune connexion à l'annuaire // Synchronisation impossible si aucune connexion à l'annuaire
if (!$this->ldap->connect()) { if (!$this->ldap->connect()) {
$this->writeln("Synchronisation impossible connexion impossible à l'annuaire"); $this->writeln("Synchronisation impossible connexion impossible à l'annuaire");
return Command::FAILURE; return Command::FAILURE;
} }
@ -191,15 +185,15 @@ class SynchroCommand extends Command
$this->writeln('== NIVEAU01 ========================================='); $this->writeln('== NIVEAU01 =========================================');
$ldapentrys = $this->ldap->search($this->filtergroup, [$this->groupgid, $this->groupname, $this->groupmember], $this->baseniveau01); $ldapentrys = $this->ldap->search($this->filtergroup, [$this->groupgid, $this->groupname, $this->groupmember], $this->baseniveau01);
foreach ($ldapentrys as $ldapentry) { foreach ($ldapentrys as $ldapentry) {
$niveau01other=$this->em->getRepository("App\Entity\Niveau01")->findOneBy(["label"=>$ldapentry[$this->groupname]]); $niveau01other = $this->em->getRepository("App\Entity\Niveau01")->findOneBy(['label' => $ldapentry[$this->groupname]]);
if ($niveau01other && $niveau01other->getIdexternal() != $ldapentry[$this->groupgid]) { if ($niveau01other && $niveau01other->getIdexternal() != $ldapentry[$this->groupgid]) {
$this->writelnred(" > ".$ldapentry[$this->groupname]." = Impossible à synchroniser un autre niveau01 existe déjà avec ce label"); $this->writelnred(' > '.$ldapentry[$this->groupname].' = Impossible à synchroniser un autre niveau01 existe déjà avec ce label');
continue; continue;
} }
// On recherche le groupe via le gid // On recherche le groupe via le gid
$this->writeln(' > '.$ldapentry[$this->groupname]); $this->writeln(' > '.$ldapentry[$this->groupname]);
$niveau01=$this->em->getRepository("App\Entity\Niveau01")->findOneBy(["idexternal"=>$ldapentry[$this->groupgid]]); $niveau01 = $this->em->getRepository("App\Entity\Niveau01")->findOneBy(['idexternal' => $ldapentry[$this->groupgid]]);
if (!$niveau01) { if (!$niveau01) {
$niveau01 = new Niveau01(); $niveau01 = new Niveau01();
$niveau01->setApikey(Uuid::uuid4()); $niveau01->setApikey(Uuid::uuid4());
@ -207,7 +201,7 @@ class SynchroCommand extends Command
} }
$niveau01->setIdexternal($ldapentry[$this->groupgid]); $niveau01->setIdexternal($ldapentry[$this->groupgid]);
$niveau01->setLabel($ldapentry[$this->groupname]); $niveau01->setLabel($ldapentry[$this->groupname]);
$niveau01->setLdapfilter("(".$this->groupname."=".$ldapentry[$this->groupname].")"); $niveau01->setLdapfilter('('.$this->groupname.'='.$ldapentry[$this->groupname].')');
$this->em->flush(); $this->em->flush();
@ -218,22 +212,24 @@ class SynchroCommand extends Command
if (!empty($ldapentry[$this->groupmember])) { if (!empty($ldapentry[$this->groupmember])) {
if (!is_array($ldapentry[$this->groupmember])) { if (!is_array($ldapentry[$this->groupmember])) {
$member = $ldapentry[$this->groupmember]; $member = $ldapentry[$this->groupmember];
if(!array_key_exists($member,$tbniveau01members)) $tbniveau01members[$member]=[]; if (!array_key_exists($member, $tbniveau01members)) {
array_push($tbniveau01members[$member],$ldapentry[$this->groupname]); $tbniveau01members[$member] = [];
} }
else { array_push($tbniveau01members[$member], $ldapentry[$this->groupname]);
} else {
foreach ($ldapentry[$this->groupmember] as $member) { foreach ($ldapentry[$this->groupmember] as $member) {
if(!array_key_exists($member,$tbniveau01members)) $tbniveau01members[$member]=[]; if (!array_key_exists($member, $tbniveau01members)) {
$tbniveau01members[$member] = [];
}
array_push($tbniveau01members[$member], $ldapentry[$this->groupname]); array_push($tbniveau01members[$member], $ldapentry[$this->groupname]);
} }
} }
} }
} }
} } else {
else {
$this->writeln(''); $this->writeln('');
$this->writeln('== NIVEAU01 ========================================='); $this->writeln('== NIVEAU01 =========================================');
$this->writelnred(" > Synchronisation impossible il vous manque des paramétres ldap pour le faire"); $this->writelnred(' > Synchronisation impossible il vous manque des paramétres ldap pour le faire');
} }
// Synchronisation des groups // Synchronisation des groups
@ -243,15 +239,15 @@ class SynchroCommand extends Command
$ldapentrys = $this->ldap->search($this->filtergroup, [$this->groupgid, $this->groupname, $this->groupmember], $this->basegroup); $ldapentrys = $this->ldap->search($this->filtergroup, [$this->groupgid, $this->groupname, $this->groupmember], $this->basegroup);
foreach ($ldapentrys as $ldapentry) { foreach ($ldapentrys as $ldapentry) {
$groupother=$this->em->getRepository("App\Entity\Group")->findOneBy(["label"=>$ldapentry[$this->groupname]]); $groupother = $this->em->getRepository("App\Entity\Group")->findOneBy(['label' => $ldapentry[$this->groupname]]);
if ($groupother && $groupother->getIdexternal() != $ldapentry[$this->groupgid]) { if ($groupother && $groupother->getIdexternal() != $ldapentry[$this->groupgid]) {
$this->writelnred(" > ".$ldapentry[$this->groupname]." = Impossible à synchroniser un autre groupe existe déjà avec ce label"); $this->writelnred(' > '.$ldapentry[$this->groupname].' = Impossible à synchroniser un autre groupe existe déjà avec ce label');
continue; continue;
} }
// On recherche le groupe via le gid // On recherche le groupe via le gid
$this->writeln(' > '.$ldapentry[$this->groupname]); $this->writeln(' > '.$ldapentry[$this->groupname]);
$group=$this->em->getRepository("App\Entity\Group")->findOneBy(["idexternal"=>$ldapentry[$this->groupgid]]); $group = $this->em->getRepository("App\Entity\Group")->findOneBy(['idexternal' => $ldapentry[$this->groupgid]]);
if (!$group) { if (!$group) {
$group = new Group(); $group = new Group();
$group->setIsopen(false); $group->setIsopen(false);
@ -262,7 +258,7 @@ class SynchroCommand extends Command
} }
$group->setIdexternal($ldapentry[$this->groupgid]); $group->setIdexternal($ldapentry[$this->groupgid]);
$group->setLabel($ldapentry[$this->groupname]); $group->setLabel($ldapentry[$this->groupname]);
$group->setLdapfilter("(".$this->groupname."=".$ldapentry[$this->groupname].")"); $group->setLdapfilter('('.$this->groupname.'='.$ldapentry[$this->groupname].')');
$this->em->flush(); $this->em->flush();
@ -273,25 +269,26 @@ class SynchroCommand extends Command
if (!empty($ldapentry[$this->groupmember])) { if (!empty($ldapentry[$this->groupmember])) {
if (!is_array($ldapentry[$this->groupmember])) { if (!is_array($ldapentry[$this->groupmember])) {
$member = $ldapentry[$this->groupmember]; $member = $ldapentry[$this->groupmember];
if(!array_key_exists($member,$tbgroupmembers)) $tbgroupmembers[$member]=[]; if (!array_key_exists($member, $tbgroupmembers)) {
array_push($tbgroupmembers[$member],$ldapentry[$this->groupname]); $tbgroupmembers[$member] = [];
} }
else { array_push($tbgroupmembers[$member], $ldapentry[$this->groupname]);
} else {
foreach ($ldapentry[$this->groupmember] as $member) { foreach ($ldapentry[$this->groupmember] as $member) {
if(!array_key_exists($member,$tbgroupmembers)) $tbgroupmembers[$member]=[]; if (!array_key_exists($member, $tbgroupmembers)) {
$tbgroupmembers[$member] = [];
}
array_push($tbgroupmembers[$member], $ldapentry[$this->groupname]); array_push($tbgroupmembers[$member], $ldapentry[$this->groupname]);
} }
} }
} }
} }
} } else {
else {
$this->writeln(''); $this->writeln('');
$this->writeln('== GROUP ============================================'); $this->writeln('== GROUP ============================================');
$this->writelnred(" > Synchronisation impossible il vous manque des paramétres ldap pour le faire"); $this->writelnred(' > Synchronisation impossible il vous manque des paramétres ldap pour le faire');
} }
// Synchronisation des users // Synchronisation des users
if ($fgsynchrousers) { if ($fgsynchrousers) {
$this->writeln(''); $this->writeln('');
@ -299,56 +296,70 @@ class SynchroCommand extends Command
$ldapentrys = $this->ldap->search($this->filteruser, [$this->username, $this->firstname, $this->lastname, $this->email, $this->avatar, $this->memberof], $this->baseuser); $ldapentrys = $this->ldap->search($this->filteruser, [$this->username, $this->firstname, $this->lastname, $this->email, $this->avatar, $this->memberof], $this->baseuser);
foreach ($ldapentrys as $ldapentry) { foreach ($ldapentrys as $ldapentry) {
$userother=$this->em->getRepository("App\Entity\User")->findOneBy(["email"=>$ldapentry[$this->email]]); $userother = $this->em->getRepository("App\Entity\User")->findOneBy(['email' => $ldapentry[$this->email]]);
if ($userother && $userother->getUSername() != $ldapentry[$this->username]) { if ($userother && $userother->getUSername() != $ldapentry[$this->username]) {
$this->writelnred(" > ".$ldapentry[$this->groupname]." = Impossible à synchroniser un autre user existe déjà avec ce mail"); $this->writelnred(' > '.$ldapentry[$this->groupname].' = Impossible à synchroniser un autre user existe déjà avec ce mail');
continue; continue;
} }
$userother=$this->em->getRepository("App\Entity\Registration")->findOneBy(["email"=>$ldapentry[$this->email]]); $userother = $this->em->getRepository("App\Entity\Registration")->findOneBy(['email' => $ldapentry[$this->email]]);
if ($userother && $userother->getUSername() != $ldapentry[$this->username]) { if ($userother && $userother->getUSername() != $ldapentry[$this->username]) {
$this->writelnred(" > ".$ldapentry[$this->username]." = Impossible à synchroniser un autre user existe déjà avec ce mail"); $this->writelnred(' > '.$ldapentry[$this->username].' = Impossible à synchroniser un autre user existe déjà avec ce mail');
continue; continue;
} }
// On recherche le user via le username // On recherche le user via le username
$this->writeln(' > '.$ldapentry[$this->username]); $this->writeln(' > '.$ldapentry[$this->username]);
$user=$this->em->getRepository("App\Entity\User")->findOneBy(["username"=>$ldapentry[$this->username]]); $user = $this->em->getRepository("App\Entity\User")->findOneBy(['username' => $ldapentry[$this->username]]);
if (!$user) { if (!$user) {
$user = new User(); $user = new User();
$user->setUsername($ldapentry[$this->username]); $user->setUsername($ldapentry[$this->username]);
$user->setIsvisible(true); $user->setIsvisible(true);
$user->setApikey(Uuid::uuid4()); $user->setApikey(Uuid::uuid4());
$user->setRole("ROLE_USER"); $user->setRole('ROLE_USER');
$user->setAvatar("noavatar.png"); $user->setAvatar('noavatar.png');
$uuid = Uuid::uuid4(); $uuid = Uuid::uuid4();
$user->setPassword("PWD-".$ldapentry[$this->username]."-".$uuid); $user->setPassword('PWD-'.$ldapentry[$this->username].'-'.$uuid);
$this->em->persist($user); $this->em->persist($user);
} }
// Recherche du niveau01 // Recherche du niveau01
$niveau01 = null; $niveau01 = null;
if($user->getNiveau01()&&empty($user->getNiveau01()->getIdexternal())) if ($user->getNiveau01() && empty($user->getNiveau01()->getIdexternal())) {
$niveau01 = $user->getNiveau01(); $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 (array_key_exists($ldapentry[$this->username], $tbniveau01members)) {
if(!$niveau01) $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); $niveau01 = $this->em->getRepository('App\Entity\Niveau01')->find(-1);
}
// Mise à jour des attributs // Mise à jour des attributs
if(!empty($ldapentry[$this->lastname])) $user->setLastname($ldapentry[$this->lastname]); if (!empty($ldapentry[$this->lastname])) {
if(!empty($ldapentry[$this->firstname])) $user->setFirstname($ldapentry[$this->firstname]); $user->setLastname($ldapentry[$this->lastname]);
if(!empty($ldapentry[$this->email])) $user->setEmail($ldapentry[$this->email]); }
if(!empty($ldapentry[$this->avatar])) $user->setAvatar($ldapentry[$this->avatar]); 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 // Mise à jour du niveau01
if($niveau01!=$user->getNiveau01()) $user->setNiveau02(null); if ($niveau01 != $user->getNiveau01()) {
$user->setNiveau02(null);
}
$user->setNiveau01($niveau01); $user->setNiveau01($niveau01);
// Mise à jour du role // Mise à jour du role
if(in_array($ldapentry[$this->username],$this->container->getParameter("appAdmins"))) if (in_array($ldapentry[$this->username], $this->container->getParameter('appAdmins'))) {
$user->setRole("ROLE_ADMIN"); $user->setRole('ROLE_ADMIN');
}
// Sauvegarde en bdd // Sauvegarde en bdd
$this->em->flush(); $this->em->flush();
@ -359,9 +370,9 @@ class SynchroCommand extends Command
// Inscription au groupe // Inscription au groupe
if (array_key_exists($ldapentry[$this->username], $tbgroupmembers)) { if (array_key_exists($ldapentry[$this->username], $tbgroupmembers)) {
foreach ($tbgroupmembers[$ldapentry[$this->username]] as $grouplabel) { foreach ($tbgroupmembers[$ldapentry[$this->username]] as $grouplabel) {
$group=$this->em->getRepository("App\Entity\Group")->findOneBy(["label"=>$grouplabel]); $group = $this->em->getRepository("App\Entity\Group")->findOneBy(['label' => $grouplabel]);
if ($group) { if ($group) {
$usergroup=$this->em->getRepository("App\Entity\UserGroup")->findOneBy(["user"=>$user,"group"=>$group]); $usergroup = $this->em->getRepository("App\Entity\UserGroup")->findOneBy(['user' => $user, 'group' => $group]);
if (!$usergroup) { if (!$usergroup) {
$usergroup = new UserGroup(); $usergroup = new UserGroup();
$usergroup->setUser($user); $usergroup->setUser($user);
@ -378,7 +389,7 @@ class SynchroCommand extends Command
// Desinscription des group ldap // Desinscription des group ldap
foreach ($ldapgroups as $group) { foreach ($ldapgroups as $group) {
if (!array_key_exists($ldapentry[$this->username], $tbgroupmembers) || !in_array($group->getLabel(), $tbgroupmembers[$ldapentry[$this->username]])) { 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]); $usergroup = $this->em->getRepository("App\Entity\UserGroup")->findOneBy(['user' => $user, 'group' => $group]);
if ($usergroup) { if ($usergroup) {
$this->em->remove($usergroup); $this->em->remove($usergroup);
$this->em->flush(); $this->em->flush();
@ -386,11 +397,10 @@ class SynchroCommand extends Command
} }
} }
} }
} } else {
else {
$this->writeln(''); $this->writeln('');
$this->writeln('== USER ============================================='); $this->writeln('== USER =============================================');
$this->writelnred(" > Synchronisation impossible il vous manque des paramétres ldap pour le faire"); $this->writelnred(' > Synchronisation impossible il vous manque des paramétres ldap pour le faire');
} }
// Purge des users // Purge des users
@ -420,8 +430,7 @@ class SynchroCommand extends Command
if ($group->getId() > 0) { if ($group->getId() > 0) {
$this->writeln(' > '.$group->getLabel()); $this->writeln(' > '.$group->getLabel());
$this->em->remove($group); $this->em->remove($group);
} } else {
else {
$group->setLdapfilter(null); $group->setLdapfilter(null);
$group->setIdexternal(null); $group->setIdexternal(null);
} }
@ -439,7 +448,7 @@ class SynchroCommand extends Command
foreach ($ldapniveau01s as $niveau01) { foreach ($ldapniveau01s as $niveau01) {
if (!in_array($niveau01->getLabel(), $tbniveau01s)) { if (!in_array($niveau01->getLabel(), $tbniveau01s)) {
if ($niveau01->getId() > 0) { if ($niveau01->getId() > 0) {
$user=$this->em->getRepository("App\Entity\User")->findOneBy(["niveau01"=>$niveau01]); $user = $this->em->getRepository("App\Entity\User")->findOneBy(['niveau01' => $niveau01]);
if ($user) { if ($user) {
$resetniveau01 = $this->em->getRepository("App\Entity\User")->find(-1); $resetniveau01 = $this->em->getRepository("App\Entity\User")->find(-1);
$user->setNiveau01($resetniveau01); $user->setNiveau01($resetniveau01);
@ -448,8 +457,7 @@ class SynchroCommand extends Command
$this->writeln(' > '.$niveau01->getLabel()); $this->writeln(' > '.$niveau01->getLabel());
$this->em->remove($niveau01); $this->em->remove($niveau01);
} } else {
else {
$niveau01->setLdapfilter(null); $niveau01->setLdapfilter(null);
$niveau01->setIdexternal(null); $niveau01->setIdexternal(null);
} }
@ -459,30 +467,26 @@ class SynchroCommand extends Command
} }
} }
return Command::SUCCESS; return Command::SUCCESS;
} }
private function nine2ldap() private function nine2ldap()
{ {
$this->writelnred(''); $this->writelnred('');
$this->writelnred('== app:Synchro'); $this->writelnred('== app:Synchro');
$this->writelnred('=========================================================================================================='); $this->writelnred('==========================================================================================================');
// Synchronisation impossible si aucune connexion à l'annuaire // Synchronisation impossible si aucune connexion à l'annuaire
if (!$this->ldap->isNine2Ldap()) { if (!$this->ldap->isNine2Ldap()) {
$this->writeln("Synchronisation impossible soit :"); $this->writeln('Synchronisation impossible soit :');
$this->writeln("- connexion impossible à l'annuaire"); $this->writeln("- connexion impossible à l'annuaire");
$this->writeln("- appMasteridentity!=SQL"); $this->writeln('- appMasteridentity!=SQL');
$this->writeln("- votre user ldap n'a pas de permission en écriture"); $this->writeln("- votre user ldap n'a pas de permission en écriture");
$this->writeln("- vous n'avez pas renseigné les bases de votre organisation"); $this->writeln("- vous n'avez pas renseigné les bases de votre organisation");
return Command::FAILURE; return Command::FAILURE;
} }
$this->writeln(''); $this->writeln('');
$this->writeln('====================================================='); $this->writeln('=====================================================');
$this->writeln('== SYNCHONISATION NINE TO LDAP ======================'); $this->writeln('== SYNCHONISATION NINE TO LDAP ======================');
@ -502,24 +506,23 @@ class SynchroCommand extends Command
$users = $this->em->getRepository("App\Entity\User")->findAll(); $users = $this->em->getRepository("App\Entity\User")->findAll();
$attributes = $this->ldap->listAttributesUser(); $attributes = $this->ldap->listAttributesUser();
foreach ($users as $user) { foreach ($users as $user) {
$filter=str_replace("*",$user->getUsername(),$this->filteruser); $filter = str_replace('*', $user->getUsername(), $this->filteruser);
$ldapentrys = $this->ldap->search($filter, $attributes, $this->baseuser); $ldapentrys = $this->ldap->search($filter, $attributes, $this->baseuser);
if (empty($ldapentrys)) { if (empty($ldapentrys)) {
$this->writeln($user->getUsername()." = SUBMIT"); $this->writeln($user->getUsername().' = SUBMIT');
$this->ldap->addUser($user); $this->ldap->addUser($user);
} } elseif ($this->ldap->ismodifyUser($user, $ldapentrys[0])) {
elseif($this->ldap->ismodifyUser($user,$ldapentrys[0])) { $this->writeln($user->getUsername().' = UPDATE');
$this->writeln($user->getUsername()." = UPDATE");
$this->ldap->modifyUser($user); $this->ldap->modifyUser($user);
} }
} }
$ldapentrys = $this->ldap->search($this->filteruser, $attributes, $this->baseuser); $ldapentrys = $this->ldap->search($this->filteruser, $attributes, $this->baseuser);
foreach ($ldapentrys as $ldapentry) { foreach ($ldapentrys as $ldapentry) {
$user=$this->em->getRepository("App\Entity\User")->findOneBy(["username"=>$ldapentry["uid"]]); $user = $this->em->getRepository("App\Entity\User")->findOneBy(['username' => $ldapentry['uid']]);
if (!$user) { if (!$user) {
$this->writeln($ldapentry["uid"]." = DELETE"); $this->writeln($ldapentry['uid'].' = DELETE');
$dn=$this->ldap->getUserDN($ldapentry["uid"]); $dn = $this->ldap->getUserDN($ldapentry['uid']);
$this->ldap->deleteByDN($dn); $this->ldap->deleteByDN($dn);
} }
} }
@ -534,29 +537,28 @@ class SynchroCommand extends Command
$this->em->flush(); $this->em->flush();
} }
$filter="gidnumber=".$group->getId(); $filter = 'gidnumber='.$group->getId();
$ldapentrys = $this->ldap->search($filter, $attributes, $this->basegroup); $ldapentrys = $this->ldap->search($filter, $attributes, $this->basegroup);
if (empty($ldapentrys)) { if (empty($ldapentrys)) {
$filter=str_replace("*",$group->getLabel(),$this->filtergroup); $filter = str_replace('*', $group->getLabel(), $this->filtergroup);
$ldapentrys = $this->ldap->search($filter, $attributes, $this->baseniveau01); $ldapentrys = $this->ldap->search($filter, $attributes, $this->baseniveau01);
} }
if (empty($ldapentrys)) { if (empty($ldapentrys)) {
$this->writeln($group->getLabel()." = SUBMIT"); $this->writeln($group->getLabel().' = SUBMIT');
$this->ldap->addGroup($group); $this->ldap->addGroup($group);
} } elseif ($this->ldap->ismodifyGroup($group, $ldapentrys[0])) {
elseif($this->ldap->ismodifyGroup($group,$ldapentrys[0])) { $this->writeln($group->getLabel().' = UPDATE');
$this->writeln($group->getLabel()." = UPDATE"); $this->ldap->modifyGroup($group, $ldapentrys[0]['cn']);
$this->ldap->modifyGroup($group,$ldapentrys[0]["cn"]);
} }
} }
$ldapentrys = $this->ldap->search($this->filtergroup, $attributes, $this->basegroup); $ldapentrys = $this->ldap->search($this->filtergroup, $attributes, $this->basegroup);
foreach ($ldapentrys as $ldapentry) { foreach ($ldapentrys as $ldapentry) {
$group=$this->em->getRepository("App\Entity\Group")->find($ldapentry["gidnumber"]); $group = $this->em->getRepository("App\Entity\Group")->find($ldapentry['gidnumber']);
if (!$group) { if (!$group) {
$this->writeln($ldapentry["cn"]." = DELETE"); $this->writeln($ldapentry['cn'].' = DELETE');
$dn=$this->ldap->getGroupDN($ldapentry["cn"]); $dn = $this->ldap->getGroupDN($ldapentry['cn']);
$this->ldap->deleteByDN($dn); $this->ldap->deleteByDN($dn);
} }
} }
@ -566,29 +568,28 @@ class SynchroCommand extends Command
$niveau02s = $this->em->getRepository("App\Entity\Niveau02")->findAll(); $niveau02s = $this->em->getRepository("App\Entity\Niveau02")->findAll();
$attributes = $this->ldap->listAttributesNiveau02(); $attributes = $this->ldap->listAttributesNiveau02();
foreach ($niveau02s as $niveau02) { foreach ($niveau02s as $niveau02) {
$filter="gidnumber=".$niveau02->getId(); $filter = 'gidnumber='.$niveau02->getId();
$ldapentrys = $this->ldap->search($filter, $attributes, $this->baseniveau02); $ldapentrys = $this->ldap->search($filter, $attributes, $this->baseniveau02);
if (empty($ldapentrys)) { if (empty($ldapentrys)) {
$filter=str_replace("*",$niveau02->getLabel(),$this->filtergroup); $filter = str_replace('*', $niveau02->getLabel(), $this->filtergroup);
$ldapentrys = $this->ldap->search($filter, $attributes, $this->baseniveau01); $ldapentrys = $this->ldap->search($filter, $attributes, $this->baseniveau01);
} }
if (empty($ldapentrys)) { if (empty($ldapentrys)) {
$this->writeln($niveau02->getLabel()." = SUBMIT"); $this->writeln($niveau02->getLabel().' = SUBMIT');
$this->ldap->addNiveau02($niveau02); $this->ldap->addNiveau02($niveau02);
} } elseif ($this->ldap->ismodifyNiveau02($niveau02, $ldapentrys[0])) {
elseif($this->ldap->ismodifyNiveau02($niveau02,$ldapentrys[0])) { $this->writeln($niveau02->getLabel().' = UPDATE');
$this->writeln($niveau02->getLabel()." = UPDATE"); $this->ldap->modifyNiveau02($niveau02, $ldapentrys[0]['cn']);
$this->ldap->modifyNiveau02($niveau02,$ldapentrys[0]["cn"]);
} }
} }
$ldapentrys = $this->ldap->search($this->filtergroup, $attributes, $this->baseniveau02); $ldapentrys = $this->ldap->search($this->filtergroup, $attributes, $this->baseniveau02);
foreach ($ldapentrys as $ldapentry) { foreach ($ldapentrys as $ldapentry) {
$niveau02=$this->em->getRepository("App\Entity\Niveau02")->find($ldapentry["gidnumber"]); $niveau02 = $this->em->getRepository("App\Entity\Niveau02")->find($ldapentry['gidnumber']);
if (!$niveau02) { if (!$niveau02) {
$this->writeln($ldapentry["cn"]." = DELETE"); $this->writeln($ldapentry['cn'].' = DELETE');
$dn=$this->ldap->getNiveau02DN($ldapentry["cn"]); $dn = $this->ldap->getNiveau02DN($ldapentry['cn']);
$this->ldap->deleteByDN($dn); $this->ldap->deleteByDN($dn);
} }
} }
@ -603,29 +604,28 @@ class SynchroCommand extends Command
$this->em->flush(); $this->em->flush();
} }
$filter="gidnumber=".$niveau01->getId(); $filter = 'gidnumber='.$niveau01->getId();
$ldapentrys = $this->ldap->search($filter, $attributes, $this->baseniveau01); $ldapentrys = $this->ldap->search($filter, $attributes, $this->baseniveau01);
if (empty($ldapentrys)) { if (empty($ldapentrys)) {
$filter=str_replace("*",$niveau01->getLabel(),$this->filtergroup); $filter = str_replace('*', $niveau01->getLabel(), $this->filtergroup);
$ldapentrys = $this->ldap->search($filter, $attributes, $this->baseniveau01); $ldapentrys = $this->ldap->search($filter, $attributes, $this->baseniveau01);
} }
if (empty($ldapentrys)) { if (empty($ldapentrys)) {
$this->writeln($niveau01->getLabel()." = SUBMIT"); $this->writeln($niveau01->getLabel().' = SUBMIT');
$this->ldap->addNiveau01($niveau01); $this->ldap->addNiveau01($niveau01);
} } elseif ($this->ldap->ismodifyNiveau01($niveau01, $ldapentrys[0])) {
elseif($this->ldap->ismodifyNiveau01($niveau01,$ldapentrys[0])) { $this->writeln($niveau01->getLabel().' = UPDATE');
$this->writeln($niveau01->getLabel()." = UPDATE"); $this->ldap->modifyNiveau01($niveau01, $ldapentrys[0]['cn']);
$this->ldap->modifyNiveau01($niveau01,$ldapentrys[0]["cn"]);
} }
} }
$ldapentrys = $this->ldap->search($this->filtergroup, $attributes, $this->baseniveau01); $ldapentrys = $this->ldap->search($this->filtergroup, $attributes, $this->baseniveau01);
foreach ($ldapentrys as $ldapentry) { foreach ($ldapentrys as $ldapentry) {
$niveau01=$this->em->getRepository("App\Entity\Niveau01")->find($ldapentry["gidnumber"]); $niveau01 = $this->em->getRepository("App\Entity\Niveau01")->find($ldapentry['gidnumber']);
if (!$niveau01) { if (!$niveau01) {
$this->writeln($ldapentry["cn"]." = DELETE"); $this->writeln($ldapentry['cn'].' = DELETE');
$dn=$this->ldap->getNiveau01DN($ldapentry["cn"]); $dn = $this->ldap->getNiveau01DN($ldapentry['cn']);
$this->ldap->deleteByDN($dn); $this->ldap->deleteByDN($dn);
} }
} }
@ -635,25 +635,25 @@ class SynchroCommand extends Command
private function nine2nine() private function nine2nine()
{ {
$this->writelnred(''); $this->writelnred('');
$this->writelnred('== app:Synchro'); $this->writelnred('== app:Synchro');
$this->writelnred('=========================================================================================================='); $this->writelnred('==========================================================================================================');
// Synchronisation ldap2nine possible uniquement si appMasteridentity=NINE // Synchronisation ldap2nine possible uniquement si appMasteridentity=NINE
if($this->appMasteridentity!="NINE") { if ('NINE' != $this->appMasteridentity) {
$this->writeln("Synchronisation impossible si appMasteridentity!=NINE"); $this->writeln('Synchronisation impossible si appMasteridentity!=NINE');
return Command::FAILURE; return Command::FAILURE;
} }
$nineurl = $this->container->getParameter("nineUrl"); $nineurl = $this->container->getParameter('nineUrl');
$ninesecret = $this->container->getParameter("nineSecret"); $ninesecret = $this->container->getParameter('nineSecret');
if (!$nineurl || !$ninesecret) { if (!$nineurl || !$ninesecret) {
$this->writeln("Synchronisation impossible soit parametres NINE_URL et/ou NINE_SECRET manquant"); $this->writeln('Synchronisation impossible soit parametres NINE_URL et/ou NINE_SECRET manquant');
return Command::FAILURE; return Command::FAILURE;
} }
$nineurl.="/rest/"; $nineurl .= '/rest/';
$this->writeln(''); $this->writeln('');
$this->writeln('====================================================='); $this->writeln('=====================================================');
@ -669,25 +669,27 @@ class SynchroCommand extends Command
$tbgroups = []; $tbgroups = [];
$tbusers = []; $tbusers = [];
$fgsynchropurgeniveau01s=($this->synchropurgeniveau01); $fgsynchropurgeniveau01s = $this->synchropurgeniveau01;
$fgsynchropurgegroups=($this->synchropurgegroup); $fgsynchropurgegroups = $this->synchropurgegroup;
$fgsynchropurgeusers=($this->synchropurgeuser); $fgsynchropurgeusers = $this->synchropurgeuser;
$this->writeln(''); $this->writeln('');
$this->writeln('== NIVEAU01 ========================================='); $this->writeln('== NIVEAU01 =========================================');
$response = $this->apiservice->run("GET",$nineurl."getAllNiveau01s",null,["key"=>$ninesecret]); $response = $this->apiservice->run('GET', $nineurl.'getAllNiveau01s', null, ['key' => $ninesecret]);
if($response->code!="200") return Command::FAILURE; if ('200' != $response->code) {
return Command::FAILURE;
}
foreach ($response->body as $nineniveau01) { foreach ($response->body as $nineniveau01) {
$niveau01other=$this->em->getRepository("App\Entity\Niveau01")->findOneBy(["label"=>$nineniveau01->niveau01label]); $niveau01other = $this->em->getRepository("App\Entity\Niveau01")->findOneBy(['label' => $nineniveau01->niveau01label]);
if ($niveau01other && $niveau01other->getIdexternal() != $nineniveau01->niveau01id) { if ($niveau01other && $niveau01other->getIdexternal() != $nineniveau01->niveau01id) {
$this->writelnred(" > ".$nineniveau01->niveau01label." = Impossible à synchroniser un autre niveau01 existe déjà avec ce label"); $this->writelnred(' > '.$nineniveau01->niveau01label.' = Impossible à synchroniser un autre niveau01 existe déjà avec ce label');
continue; continue;
} }
// On recherche le groupe via le gid // On recherche le groupe via le gid
$this->writeln(' > '.$nineniveau01->niveau01label); $this->writeln(' > '.$nineniveau01->niveau01label);
$niveau01=$this->em->getRepository("App\Entity\Niveau01")->findOneBy(["idexternal"=>$nineniveau01->niveau01id]); $niveau01 = $this->em->getRepository("App\Entity\Niveau01")->findOneBy(['idexternal' => $nineniveau01->niveau01id]);
if (!$niveau01) { if (!$niveau01) {
$niveau01 = new Niveau01(); $niveau01 = new Niveau01();
$niveau01->setApikey(Uuid::uuid4()); $niveau01->setApikey(Uuid::uuid4());
@ -704,7 +706,9 @@ class SynchroCommand extends Command
// Sauvegarde des membres du niveau01 // Sauvegarde des membres du niveau01
if (!empty($nineniveau01->niveau01users)) { if (!empty($nineniveau01->niveau01users)) {
foreach ($nineniveau01->niveau01users as $member) { foreach ($nineniveau01->niveau01users as $member) {
if(!array_key_exists($member->userlogin,$tbniveau01members)) $tbniveau01members[$member->userlogin]=[]; if (!array_key_exists($member->userlogin, $tbniveau01members)) {
$tbniveau01members[$member->userlogin] = [];
}
array_push($tbniveau01members[$member->userlogin], $nineniveau01->niveau01label); array_push($tbniveau01members[$member->userlogin], $nineniveau01->niveau01label);
} }
} }
@ -713,18 +717,20 @@ class SynchroCommand extends Command
$this->writeln(''); $this->writeln('');
$this->writeln('== GROUP ============================================'); $this->writeln('== GROUP ============================================');
$response = $this->apiservice->run("GET",$nineurl."getAllGroups",null,["key"=>$ninesecret]); $response = $this->apiservice->run('GET', $nineurl.'getAllGroups', null, ['key' => $ninesecret]);
if($response->code!="200") return Command::FAILURE; if ('200' != $response->code) {
return Command::FAILURE;
}
foreach ($response->body as $ninegroup) { foreach ($response->body as $ninegroup) {
$groupother=$this->em->getRepository("App\Entity\Group")->findOneBy(["label"=>$ninegroup->grouplabel]); $groupother = $this->em->getRepository("App\Entity\Group")->findOneBy(['label' => $ninegroup->grouplabel]);
if ($groupother && $groupother->getIdexternal() != $ninegroup->groupid) { if ($groupother && $groupother->getIdexternal() != $ninegroup->groupid) {
$this->writelnred(" > ".$ninegroup->grouplabel." = Impossible à synchroniser un autre group existe déjà avec ce label"); $this->writelnred(' > '.$ninegroup->grouplabel.' = Impossible à synchroniser un autre group existe déjà avec ce label');
continue; continue;
} }
// On recherche le groupe via le gid // On recherche le groupe via le gid
$this->writeln(' > '.$ninegroup->grouplabel); $this->writeln(' > '.$ninegroup->grouplabel);
$group=$this->em->getRepository("App\Entity\Group")->findOneBy(["idexternal"=>$ninegroup->groupid]); $group = $this->em->getRepository("App\Entity\Group")->findOneBy(['idexternal' => $ninegroup->groupid]);
if (!$group) { if (!$group) {
$group = new Group(); $group = new Group();
$group->setIsopen(false); $group->setIsopen(false);
@ -744,70 +750,87 @@ class SynchroCommand extends Command
// Sauvegarde des membres du group // Sauvegarde des membres du group
if (!empty($ninegroup->groupusers)) { if (!empty($ninegroup->groupusers)) {
foreach ($ninegroup->groupusers as $member) { foreach ($ninegroup->groupusers as $member) {
if(!array_key_exists($member->userlogin,$tbgroupmembers)) $tbgroupmembers[$member->userlogin]=[]; if (!array_key_exists($member->userlogin, $tbgroupmembers)) {
$tbgroupmembers[$member->userlogin] = [];
}
array_push($tbgroupmembers[$member->userlogin], $ninegroup->grouplabel); array_push($tbgroupmembers[$member->userlogin], $ninegroup->grouplabel);
} }
} }
} }
$this->writeln(''); $this->writeln('');
$this->writeln('== USER ============================================='); $this->writeln('== USER =============================================');
$response = $this->apiservice->run("GET",$nineurl."getAllUsers",null,["key"=>$ninesecret]); $response = $this->apiservice->run('GET', $nineurl.'getAllUsers', null, ['key' => $ninesecret]);
if($response->code!="200") return Command::FAILURE; if ('200' != $response->code) {
return Command::FAILURE;
}
$nineusers = $response->body; $nineusers = $response->body;
foreach ($nineusers as $nineuser) { foreach ($nineusers as $nineuser) {
$userother=$this->em->getRepository("App\Entity\User")->findOneBy(["email"=>$nineuser->useremail]); $userother = $this->em->getRepository("App\Entity\User")->findOneBy(['email' => $nineuser->useremail]);
if ($userother && $userother->getUsername() != $nineuser->userlogin) { if ($userother && $userother->getUsername() != $nineuser->userlogin) {
$this->writelnred(" > ".$nineuser->userlogin." = Impossible à synchroniser un autre user existe déjà avec ce mail"); $this->writelnred(' > '.$nineuser->userlogin.' = Impossible à synchroniser un autre user existe déjà avec ce mail');
continue; continue;
} }
$userother=$this->em->getRepository("App\Entity\Registration")->findOneBy(["email"=>$nineuser->useremail]); $userother = $this->em->getRepository("App\Entity\Registration")->findOneBy(['email' => $nineuser->useremail]);
if ($userother && $userother->getUSername() != $nineuser->userlogin) { if ($userother && $userother->getUSername() != $nineuser->userlogin) {
$this->writelnred(" > ".$nineuser->userlogin." = Impossible à synchroniser un autre user existe déjà avec ce mail"); $this->writelnred(' > '.$nineuser->userlogin.' = Impossible à synchroniser un autre user existe déjà avec ce mail');
continue; continue;
} }
// On recherche le user via le username // On recherche le user via le username
$this->writeln(' > '.$nineuser->userlogin); $this->writeln(' > '.$nineuser->userlogin);
$user=$this->em->getRepository("App\Entity\User")->findOneBy(["username"=>$nineuser->userlogin]); $user = $this->em->getRepository("App\Entity\User")->findOneBy(['username' => $nineuser->userlogin]);
if (!$user) { if (!$user) {
$user = new User(); $user = new User();
$user->setUsername($nineuser->userlogin); $user->setUsername($nineuser->userlogin);
$user->setIsvisible(true); $user->setIsvisible(true);
$user->setApikey(Uuid::uuid4()); $user->setApikey(Uuid::uuid4());
$user->setRole("ROLE_USER"); $user->setRole('ROLE_USER');
$user->setAvatar($nineuser->useravatar); $user->setAvatar($nineuser->useravatar);
$uuid = Uuid::uuid4(); $uuid = Uuid::uuid4();
$user->setPassword("PWD-".$nineuser->userlogin."-".$uuid); $user->setPassword('PWD-'.$nineuser->userlogin.'-'.$uuid);
$this->em->persist($user); $this->em->persist($user);
} }
// Recherche du niveau01 // Recherche du niveau01
$niveau01 = null; $niveau01 = null;
if($user->getNiveau01()&&empty($user->getNiveau01()->getIdexternal())) if ($user->getNiveau01() && empty($user->getNiveau01()->getIdexternal())) {
$niveau01 = $user->getNiveau01(); $niveau01 = $user->getNiveau01();
if(array_key_exists($nineuser->userlogin,$tbniveau01members)) }
$niveau01=$this->em->getRepository("App\Entity\Niveau01")->findOneBy(["label"=>$tbniveau01members[$nineuser->userlogin][0]]); if (array_key_exists($nineuser->userlogin, $tbniveau01members)) {
if(!$niveau01) $niveau01 = $this->em->getRepository("App\Entity\Niveau01")->findOneBy(['label' => $tbniveau01members[$nineuser->userlogin][0]]);
}
if (!$niveau01) {
$niveau01 = $this->em->getRepository('App\Entity\Niveau01')->find(-1); $niveau01 = $this->em->getRepository('App\Entity\Niveau01')->find(-1);
}
// Mise à jour des attributs // Mise à jour des attributs
if(!empty($nineuser->userlastname)) $user->setLastname($nineuser->userlastname); if (!empty($nineuser->userlastname)) {
if(!empty($nineuser->userfirstname)) $user->setFirstname($nineuser->userfirstname); $user->setLastname($nineuser->userlastname);
if(!empty($nineuser->useremail)) $user->setEmail($nineuser->useremail); }
if(!empty($nineuser->useravatar)) $user->setAvatar($nineuser->useravatar); 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 // Mise à jour du niveau01
if($niveau01!=$user->getNiveau01()) $user->setNiveau02(null); if ($niveau01 != $user->getNiveau01()) {
$user->setNiveau02(null);
}
$user->setNiveau01($niveau01); $user->setNiveau01($niveau01);
// Mise à jour du role // Mise à jour du role
if(in_array($nineuser->userlogin,$this->container->getParameter("appAdmins"))) if (in_array($nineuser->userlogin, $this->container->getParameter('appAdmins'))) {
$user->setRole("ROLE_ADMIN"); $user->setRole('ROLE_ADMIN');
}
// Sauvegarde en bdd // Sauvegarde en bdd
$this->em->flush(); $this->em->flush();
@ -818,9 +841,9 @@ class SynchroCommand extends Command
// Inscription au groupe // Inscription au groupe
if (array_key_exists($nineuser->userlogin, $tbgroupmembers)) { if (array_key_exists($nineuser->userlogin, $tbgroupmembers)) {
foreach ($tbgroupmembers[$nineuser->userlogin] as $grouplabel) { foreach ($tbgroupmembers[$nineuser->userlogin] as $grouplabel) {
$group=$this->em->getRepository("App\Entity\Group")->findOneBy(["label"=>$grouplabel]); $group = $this->em->getRepository("App\Entity\Group")->findOneBy(['label' => $grouplabel]);
if ($group) { if ($group) {
$usergroup=$this->em->getRepository("App\Entity\UserGroup")->findOneBy(["user"=>$user,"group"=>$group]); $usergroup = $this->em->getRepository("App\Entity\UserGroup")->findOneBy(['user' => $user, 'group' => $group]);
if (!$usergroup) { if (!$usergroup) {
$usergroup = new UserGroup(); $usergroup = new UserGroup();
$usergroup->setUser($user); $usergroup->setUser($user);
@ -837,7 +860,7 @@ class SynchroCommand extends Command
// Desinscription des group ldap // Desinscription des group ldap
foreach ($ninegroups as $group) { foreach ($ninegroups as $group) {
if (!array_key_exists($nineuser->userlogin, $tbgroupmembers) || !in_array($group->getLabel(), $tbgroupmembers[$nineuser->userlogin])) { 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]); $usergroup = $this->em->getRepository("App\Entity\UserGroup")->findOneBy(['user' => $user, 'group' => $group]);
if ($usergroup) { if ($usergroup) {
$this->em->remove($usergroup); $this->em->remove($usergroup);
$this->em->flush(); $this->em->flush();
@ -846,7 +869,6 @@ class SynchroCommand extends Command
} }
} }
// Purge des users // Purge des users
if ($fgsynchropurgeusers) { if ($fgsynchropurgeusers) {
$this->writeln(''); $this->writeln('');
@ -874,8 +896,7 @@ class SynchroCommand extends Command
if ($group->getId() > 0) { if ($group->getId() > 0) {
$this->writeln(' > '.$group->getLabel()); $this->writeln(' > '.$group->getLabel());
$this->em->remove($group); $this->em->remove($group);
} } else {
else {
$group->setLdapfilter(null); $group->setLdapfilter(null);
$group->setIdexternal(null); $group->setIdexternal(null);
} }
@ -893,7 +914,7 @@ class SynchroCommand extends Command
foreach ($nineniveau01s as $niveau01) { foreach ($nineniveau01s as $niveau01) {
if (!in_array($niveau01->getLabel(), $tbniveau01s)) { if (!in_array($niveau01->getLabel(), $tbniveau01s)) {
if ($niveau01->getId() > 0) { if ($niveau01->getId() > 0) {
$user=$this->em->getRepository("App\Entity\User")->findOneBy(["niveau01"=>$niveau01]); $user = $this->em->getRepository("App\Entity\User")->findOneBy(['niveau01' => $niveau01]);
if ($user) { if ($user) {
$resetniveau01 = $this->em->getRepository("App\Entity\User")->find(-1); $resetniveau01 = $this->em->getRepository("App\Entity\User")->find(-1);
$user->setNiveau01($resetniveau01); $user->setNiveau01($resetniveau01);
@ -902,8 +923,7 @@ class SynchroCommand extends Command
$this->writeln(' > '.$niveau01->getLabel()); $this->writeln(' > '.$niveau01->getLabel());
$this->em->remove($niveau01); $this->em->remove($niveau01);
} } else {
else {
$niveau01->setLdapfilter(null); $niveau01->setLdapfilter(null);
$niveau01->setIdexternal(null); $niveau01->setIdexternal(null);
} }
@ -913,22 +933,23 @@ class SynchroCommand extends Command
} }
} }
return Command::SUCCESS; return Command::SUCCESS;
} }
private function writelnred($string) { private function writelnred($string)
{
$this->output->writeln('<fg=red>'.$string.'</>'); $this->output->writeln('<fg=red>'.$string.'</>');
$this->filesystem->appendToFile($this->rootlog.'cron.log', $string."\n"); $this->filesystem->appendToFile($this->rootlog.'cron.log', $string."\n");
} }
private function writeln($string) { private function writeln($string)
{
$this->output->writeln($string); $this->output->writeln($string);
$this->filesystem->appendToFile($this->rootlog.'cron.log', $string."\n"); $this->filesystem->appendToFile($this->rootlog.'cron.log', $string."\n");
} }
protected function addUser($niveau01,$username,$firstname,$lastname,$email,$usersadmin) { protected function addUser($niveau01, $username, $firstname, $lastname, $email, $usersadmin)
{
$user = new User(); $user = new User();
$user->setUsername($username); $user->setUsername($username);
@ -938,32 +959,33 @@ class SynchroCommand extends Command
$user->setNiveau01($niveau01); $user->setNiveau01($niveau01);
$user->setSiren($niveau01->getSiren()); $user->setSiren($niveau01->getSiren());
$user->setVisible(true); $user->setVisible(true);
$user->setAuthlevel("simple"); $user->setAuthlevel('simple');
$user->setBelongingpopulation("agent"); $user->setBelongingpopulation('agent');
$uuid = Uuid::uuid4(); $uuid = Uuid::uuid4();
$user->setPassword("PWD-".$username."-".$uuid); $user->setPassword('PWD-'.$username.'-'.$uuid);
if(in_array($username,$usersadmin)) if (in_array($username, $usersadmin)) {
$user->setRole("ROLE_ADMIN"); $user->setRole('ROLE_ADMIN');
else { } else {
$user->setRole("ROLE_USER"); $user->setRole('ROLE_USER');
} }
$this->em->persist($user); $this->em->persist($user);
$this->em->flush(); $this->em->flush();
} }
protected function modUser($user,$username,$firstname,$lastname,$email,$usersadmin) { protected function modUser($user, $username, $firstname, $lastname, $email, $usersadmin)
{
$user->setLastname($lastname); $user->setLastname($lastname);
$user->setFirstname($firstname); $user->setFirstname($firstname);
$user->setEmail($email); $user->setEmail($email);
if(in_array($username,$usersadmin)) if (in_array($username, $usersadmin)) {
$user->setRole("ROLE_ADMIN"); $user->setRole('ROLE_ADMIN');
}
$this->em->persist($user); $this->em->persist($user);
$this->em->flush(); $this->em->flush();
} }
} }

View File

@ -1,37 +1,35 @@
<?php <?php
namespace App\Controller; 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\Audit as Entity; use App\Entity\Audit as Entity;
use App\Form\AuditType as Form; use Doctrine\Persistence\ManagerRegistry;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
class AuditController extends AbstractController class AuditController extends AbstractController
{ {
private $data="audit"; private $data = 'audit';
private $entity = "App\Entity\Audit"; private $entity = "App\Entity\Audit";
private $twig="Audit/"; private $twig = 'Audit/';
private $route="app_admin_audit"; private $route = 'app_admin_audit';
public function list($entityname, $access, ManagerRegistry $em): Response public function list($entityname, $access, ManagerRegistry $em): Response
{ {
$datas = $em->getRepository($this->entity)->findBy(["entityname"=>$entityname]); $datas = $em->getRepository($this->entity)->findBy(['entityname' => $entityname]);
return $this->render($this->twig.'list.html.twig', [ return $this->render($this->twig.'list.html.twig', [
$this->data."s" => $datas, $this->data.'s' => $datas,
"entityname" => $entityname, 'entityname' => $entityname,
"useheader"=>true, 'useheader' => true,
"usemenu"=>false, 'usemenu' => false,
"usesidebar"=>true, 'usesidebar' => true,
]); ]);
} }
public function auditrender($entityname, $entityid, $access, ManagerRegistry $em): Response public function auditrender($entityname, $entityid, $access, ManagerRegistry $em): Response
{ {
$datas = $em->getRepository($this->entity)->findBy(["entityname"=>$entityname,"entityid"=>$entityid]); $datas = $em->getRepository($this->entity)->findBy(['entityname' => $entityname, 'entityid' => $entityid]);
/* /*
if($entityname=="User") { if($entityname=="User") {
@ -53,7 +51,7 @@ class AuditController extends AbstractController
*/ */
return $this->render($this->twig.'render.html.twig', [ return $this->render($this->twig.'render.html.twig', [
$this->data."s" => $datas, $this->data.'s' => $datas,
]); ]);
} }
} }

View File

@ -1,37 +1,36 @@
<?php <?php
namespace App\Controller; namespace App\Controller;
use App\Form\ConfigType as Form;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response; 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 class ConfigController extends AbstractController
{ {
private $data="config"; private $data = 'config';
private $entity = "App\Entity\Config"; private $entity = "App\Entity\Config";
private $twig="Config/"; private $twig = 'Config/';
private $route="app_admin_config"; private $route = 'app_admin_config';
public function list($access): Response public function list($access): Response
{ {
return $this->render($this->twig.'list.html.twig', [ return $this->render($this->twig.'list.html.twig', [
"useheader"=>true, 'useheader' => true,
"usemenu"=>false, 'usemenu' => false,
"usesidebar"=>true, 'usesidebar' => true,
"access"=>$access, 'access' => $access,
]); ]);
} }
public function listrender($access, $category, ManagerRegistry $em): Response public function listrender($access, $category, ManagerRegistry $em): Response
{ {
$datas = $em->getRepository($this->entity)->findBy(["visible"=>true,"category"=>$category]); $datas = $em->getRepository($this->entity)->findBy(['visible' => true, 'category' => $category]);
return $this->render($this->twig.'render.html.twig', [ return $this->render($this->twig.'render.html.twig', [
$this->data."s" => $datas, $this->data.'s' => $datas,
]); ]);
} }
@ -39,11 +38,12 @@ class ConfigController extends AbstractController
{ {
// Initialisation de l'enregistrement // Initialisation de l'enregistrement
$data = $em->getRepository($this->entity)->find($id); $data = $em->getRepository($this->entity)->find($id);
if(!$data->getValue()) if (!$data->getValue()) {
$data->setValue($request->getSession()->get($data->getId())); $data->setValue($request->getSession()->get($data->getId()));
}
// Création du formulaire // Création du formulaire
$form = $this->createForm(Form::class,$data,array("mode"=>"update","id"=>$data->getId(),"type"=>$data->getType(),"required"=>$data->isRequired())); $form = $this->createForm(Form::class, $data, ['mode' => 'update', 'id' => $data->getId(), 'type' => $data->getType(), 'required' => $data->isRequired()]);
// Récupération des data du formulaire // Récupération des data du formulaire
$form->handleRequest($request); $form->handleRequest($request);
@ -64,7 +64,7 @@ class ConfigController extends AbstractController
'usesidebar' => true, 'usesidebar' => true,
$this->data => $data, $this->data => $data,
'mode' => 'update', 'mode' => 'update',
'form' => $form->createView() 'form' => $form->createView(),
]); ]);
} }
@ -73,9 +73,10 @@ class ConfigController extends AbstractController
// Récupération de l'enregistrement courant // Récupération de l'enregistrement courant
$config = $em->getRepository($this->entity)->find($id); $config = $em->getRepository($this->entity)->find($id);
if (!$config->isRequired()) { if (!$config->isRequired()) {
$config->setValue(""); $config->setValue('');
$em->getManager()->flush(); $em->getManager()->flush();
} }
return $this->redirectToRoute($this->route); return $this->redirectToRoute($this->route);
} }

View File

@ -2,31 +2,30 @@
namespace App\Controller; namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use App\Form\CronType as Form;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Doctrine\Persistence\ManagerRegistry; use Doctrine\Persistence\ManagerRegistry;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpFoundation\BinaryFileResponse; use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag; use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use App\Form\CronType as Form;
class CronController extends AbstractController class CronController extends AbstractController
{ {
private $data="cron"; private $data = 'cron';
private $entity = "App\Entity\Cron"; private $entity = "App\Entity\Cron";
private $twig="Cron/"; private $twig = 'Cron/';
private $route="app_admin_cron"; private $route = 'app_admin_cron';
public function list($access): Response public function list($access): Response
{ {
return $this->render($this->twig.'list.html.twig', [ return $this->render($this->twig.'list.html.twig', [
"useheader"=>true, 'useheader' => true,
"usemenu"=>false, 'usemenu' => false,
"usesidebar"=>true, 'usesidebar' => true,
"access"=>$access, 'access' => $access,
]); ]);
} }
@ -44,32 +43,32 @@ class CronController extends AbstractController
$total = $em->getManager()->createQueryBuilder()->select('COUNT(entity)')->from($this->entity, 'entity')->getQuery()->getSingleScalarResult(); $total = $em->getManager()->createQueryBuilder()->select('COUNT(entity)')->from($this->entity, 'entity')->getQuery()->getSingleScalarResult();
// Nombre d'enregistrement filtré // Nombre d'enregistrement filtré
if(!$search||$search["value"]=="") if (!$search || '' == $search['value']) {
$totalf = $total; $totalf = $total;
else { } else {
$totalf = $em->getManager()->createQueryBuilder() $totalf = $em->getManager()->createQueryBuilder()
->select('COUNT(entity)') ->select('COUNT(entity)')
->from($this->entity, 'entity') ->from($this->entity, 'entity')
->where('entity.command LIKE :value OR entity.description LIKE :value') ->where('entity.command LIKE :value OR entity.description LIKE :value')
->setParameter("value", "%".$search["value"]."%") ->setParameter('value', '%'.$search['value'].'%')
->getQuery() ->getQuery()
->getSingleScalarResult(); ->getSingleScalarResult();
} }
// Construction du tableau de retour // Construction du tableau de retour
$output = array( $output = [
'draw' => $draw, 'draw' => $draw,
'recordsFiltered' => $totalf, 'recordsFiltered' => $totalf,
'recordsTotal' => $total, 'recordsTotal' => $total,
'data' => array(), 'data' => [],
); ];
// Parcours des Enregistrement // Parcours des Enregistrement
$qb = $em->getManager()->createQueryBuilder(); $qb = $em->getManager()->createQueryBuilder();
$qb->select('entity')->from($this->entity, 'entity'); $qb->select('entity')->from($this->entity, 'entity');
if($search&&$search["value"]!="") { if ($search && '' != $search['value']) {
$qb->andWhere('entity.command LIKE :value OR entity.description LIKE :value') $qb->andWhere('entity.command LIKE :value OR entity.description LIKE :value')
->setParameter("value", "%".$search["value"]."%"); ->setParameter('value', '%'.$search['value'].'%');
} }
if ($ordercolumn) { if ($ordercolumn) {
@ -88,17 +87,17 @@ class CronController extends AbstractController
foreach ($datas as $data) { foreach ($datas as $data) {
// Action // Action
$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>"; $action .= "<a href='".$this->generateUrl($this->route.'_update', ['id' => $data->getId()])."'><i class='fa fa-file fa-fw fa-2x'></i></a>";
$tmp=array(); $tmp = [];
array_push($tmp, $action); array_push($tmp, $action);
array_push($tmp,$data->getNextexecdate()->format("d/m/Y H:i")); array_push($tmp, $data->getNextexecdate()->format('d/m/Y H:i'));
array_push($tmp, $data->getCommand()); array_push($tmp, $data->getCommand());
array_push($tmp, $data->getDescription()); array_push($tmp, $data->getDescription());
array_push($tmp, $data->getStatutLabel()); array_push($tmp, $data->getStatutLabel());
array_push($output["data"],$tmp); array_push($output['data'], $tmp);
} }
// Retour // Retour
@ -109,12 +108,14 @@ class CronController extends AbstractController
{ {
// Initialisation de l'enregistrement // Initialisation de l'enregistrement
$data = $em->getRepository($this->entity)->find($id); $data = $em->getRepository($this->entity)->find($id);
if (!$data) throw $this->createNotFoundException('Unable to find entity.'); if (!$data) {
throw $this->createNotFoundException('Unable to find entity.');
}
// Création du formulaire // Création du formulaire
$form = $this->createForm(Form::class,$data,array( $form = $this->createForm(Form::class, $data, [
"mode"=>"update", 'mode' => 'update',
)); ]);
// Récupération des data du formulaire // Récupération des data du formulaire
$form->handleRequest($request); $form->handleRequest($request);
@ -150,34 +151,36 @@ class CronController extends AbstractController
public function getlog(Request $request, $id) public function getlog(Request $request, $id)
{ {
$path = $this->getParameter('kernel.project_dir'); $path = $this->getParameter('kernel.project_dir');
if($id=="dump") if ('dump' == $id) {
$file = $path . '/var/log/' . $this->getParameter("appAlias") . '.sql'; $file = $path.'/var/log/'.$this->getParameter('appAlias').'.sql';
else } else {
$file = $path.'/var/log/'.$id.'.log'; $file = $path.'/var/log/'.$id.'.log';
}
$fs = new Filesystem(); $fs = new Filesystem();
if ($fs->exists($file)) { if ($fs->exists($file)) {
$response = new BinaryFileResponse($file); $response = new BinaryFileResponse($file);
$response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT); $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT);
return $response; return $response;
} else {
return $this->redirectToRoute($this->route.'_log');
} }
else return $this->redirectToRoute($this->route."_log");
} }
protected function getErrorForm($id, $form, $request, $data, $mode)
protected function getErrorForm($id,$form,$request,$data,$mode) { {
if ($form->get('submit')->isClicked()&&$mode=="delete") { if ($form->get('submit')->isClicked() && 'delete' == $mode) {
} }
if ($form->get('submit')->isClicked() && $mode=="submit") { if ($form->get('submit')->isClicked() && 'submit' == $mode) {
} }
if ($form->get('submit')->isClicked() && !$form->isValid()) { if ($form->get('submit')->isClicked() && !$form->isValid()) {
$errors = $form->getErrors(); $errors = $form->getErrors();
foreach ($errors as $error) { foreach ($errors as $error) {
$request->getSession()->getFlashBag()->add("error", $error->getMessage()); $request->getSession()->getFlashBag()->add('error', $error->getMessage());
} }
} }
} }

View File

@ -2,14 +2,14 @@
namespace App\Controller; 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;
use App\Service\MinioService; use App\Service\MinioService;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\KernelInterface;
class CropController extends AbstractController class CropController extends AbstractController
{ {
@ -29,7 +29,7 @@ class CropController extends AbstractController
'useheader' => false, 'useheader' => false,
'usesidebar' => false, 'usesidebar' => false,
'type' => $type, 'type' => $type,
'reportinput' => $reportinput 'reportinput' => $reportinput,
]); ]);
} }
@ -38,7 +38,7 @@ class CropController extends AbstractController
{ {
// Récupération de l'image à cropper // Récupération de l'image à cropper
$file = $request->query->get('file'); $file = $request->query->get('file');
$large_image_location=$this->minio->download($type."/".$file,$type."/".$file,true); $large_image_location = $this->minio->download($type.'/'.$file, $type.'/'.$file, true);
// Récupérer les tailles de l'image // Récupérer les tailles de l'image
$width = $this->getWidth($large_image_location); $width = $this->getWidth($large_image_location);
@ -49,30 +49,30 @@ class CropController extends AbstractController
// Définir le pourcentage de réduction de l'image // Définir le pourcentage de réduction de l'image
switch ($type) { switch ($type) {
case "illustration": case 'illustration':
$max_height = 0; $max_height = 0;
$ratio="1:1"; $ratio = '1:1';
break; break;
case "avatar": case 'avatar':
$max_height = 900; $max_height = 900;
$max_width = 900; $max_width = 900;
$ratio="1:1"; $ratio = '1:1';
break; break;
case "header": case 'header':
$max_height = 1600; $max_height = 1600;
$max_width = 1600; $max_width = 1600;
$ratio="16:2"; $ratio = '16:2';
break; break;
case "hero": case 'hero':
$max_height = 1600; $max_height = 1600;
$max_width = 1600; $max_width = 1600;
$ratio="16:9"; $ratio = '16:9';
break; break;
case "image": case 'image':
$max_height = 1600; $max_height = 1600;
$max_width = 1600; $max_width = 1600;
$ratio="1:1"; $ratio = '1:1';
break; break;
} }
@ -82,14 +82,15 @@ class CropController extends AbstractController
$scale = $max_width / $width; $scale = $max_width / $width;
} }
$this->resizeImage($large_image_location, $width, $height, $scale); $this->resizeImage($large_image_location, $width, $height, $scale);
$this->minio->upload($large_image_location,$type."/".$file,false); $this->minio->upload($large_image_location, $type.'/'.$file, false);
} else {
$scale = 1;
} }
else $scale=1;
// Construction du formulaire // Construction du formulaire
$submited = false; $submited = false;
$form = $this->createFormBuilder() $form = $this->createFormBuilder()
->add('submit',SubmitType::class,array("label" => "Valider","attr" => array("class" => "btn btn-success"))) ->add('submit', SubmitType::class, ['label' => 'Valider', 'attr' => ['class' => 'btn btn-success']])
->add('x', HiddenType::class) ->add('x', HiddenType::class)
->add('y', HiddenType::class) ->add('y', HiddenType::class)
->add('w', HiddenType::class) ->add('w', HiddenType::class)
@ -107,12 +108,12 @@ class CropController extends AbstractController
if ($form->get('submit')->isClicked() && $form->isValid()) { if ($form->get('submit')->isClicked() && $form->isValid()) {
// Récupération des valeurs du formulaire // Récupération des valeurs du formulaire
$data = $form->getData(); $data = $form->getData();
$tmpdir=$this->appKernel->getProjectDir()."/var/tmp"; $tmpdir = $this->appKernel->getProjectDir().'/var/tmp';
$thumb_image_location = "$tmpdir/$type/thumb_".$file; $thumb_image_location = "$tmpdir/$type/thumb_".$file;
$cropped = $this->resizeThumbnailImage($thumb_image_location, $large_image_location,$data["ws"],$data["hs"],$data["xs"],$data["ys"],$scale); $cropped = $this->resizeThumbnailImage($thumb_image_location, $large_image_location, $data['ws'], $data['hs'], $data['xs'], $data['ys'], $scale);
// Dépot des fichiers sur minio // Dépot des fichiers sur minio
$this->minio->upload($thumb_image_location,$type."/thumb_".$file,false); $this->minio->upload($thumb_image_location, $type.'/thumb_'.$file, false);
$submited = true; $submited = true;
} }
@ -124,26 +125,31 @@ class CropController extends AbstractController
'type' => $type, 'type' => $type,
'file' => $file, 'file' => $file,
'ratio' => $ratio, 'ratio' => $ratio,
"reportinput" => $reportinput, 'reportinput' => $reportinput,
"submited" => $submited 'submited' => $submited,
]); ]);
} }
// Calcul de la hauteur // Calcul de la hauteur
protected function getHeight($image) { protected function getHeight($image)
{
$size = getimagesize($image); $size = getimagesize($image);
$height = $size[1]; $height = $size[1];
return $height; return $height;
} }
// Cacul de la largeur // Cacul de la largeur
protected function getWidth($image) { protected function getWidth($image)
{
$size = getimagesize($image); $size = getimagesize($image);
$width = $size[0]; $width = $size[0];
return $width; return $width;
} }
protected function resizeImage($image,$width,$height,$scale) { protected function resizeImage($image, $width, $height, $scale)
{
list($imagewidth, $imageheight, $imageType) = getimagesize($image); list($imagewidth, $imageheight, $imageType) = getimagesize($image);
$imageType = image_type_to_mime_type($imageType); $imageType = image_type_to_mime_type($imageType);
$newImageWidth = ceil($width * $scale); $newImageWidth = ceil($width * $scale);
@ -152,41 +158,43 @@ class CropController extends AbstractController
$source = null; $source = null;
switch ($imageType) { switch ($imageType) {
case "image/gif": case 'image/gif':
$source = imagecreatefromgif($image); $source = imagecreatefromgif($image);
break; break;
case "image/pjpeg": case 'image/pjpeg':
case "image/jpeg": case 'image/jpeg':
case "image/jpg": case 'image/jpg':
$source = imagecreatefromjpeg($image); $source = imagecreatefromjpeg($image);
break; break;
case "image/png": case 'image/png':
case "image/x-png": case 'image/x-png':
$source = imagecreatefrompng($image); $source = imagecreatefrompng($image);
break; break;
} }
imagecopyresampled($newImage, $source, 0, 0, 0, 0, $newImageWidth, $newImageHeight, $width, $height); imagecopyresampled($newImage, $source, 0, 0, 0, 0, $newImageWidth, $newImageHeight, $width, $height);
switch ($imageType) { switch ($imageType) {
case "image/gif": case 'image/gif':
imagegif($newImage, $image); imagegif($newImage, $image);
break; break;
case "image/pjpeg": case 'image/pjpeg':
case "image/jpeg": case 'image/jpeg':
case "image/jpg": case 'image/jpg':
imagejpeg($newImage, $image, 90); imagejpeg($newImage, $image, 90);
break; break;
case "image/png": case 'image/png':
case "image/x-png": case 'image/x-png':
imagepng($newImage, $image); imagepng($newImage, $image);
break; break;
} }
chmod($image, 0640); chmod($image, 0640);
return $image; return $image;
} }
protected function resizeThumbnailImage($thumb_image_name, $image, $width, $height, $start_width, $start_height, $scale){ protected function resizeThumbnailImage($thumb_image_name, $image, $width, $height, $start_width, $start_height, $scale)
{
$fs = new Filesystem(); $fs = new Filesystem();
$fs->remove($thumb_image_name); $fs->remove($thumb_image_name);
@ -200,17 +208,17 @@ class CropController extends AbstractController
$source = null; $source = null;
switch ($imageType) { switch ($imageType) {
case "image/gif": case 'image/gif':
$source = imagecreatefromgif($image); $source = imagecreatefromgif($image);
break; break;
case "image/pjpeg": case 'image/pjpeg':
case "image/jpeg": case 'image/jpeg':
case "image/jpg": case 'image/jpg':
dump("here"); dump('here');
$source = imagecreatefromjpeg($image); $source = imagecreatefromjpeg($image);
break; break;
case "image/png": case 'image/png':
case "image/x-png": case 'image/x-png':
$source = imagecreatefrompng($image); $source = imagecreatefrompng($image);
break; break;
} }
@ -218,23 +226,23 @@ class CropController extends AbstractController
$ok = imagecopyresampled($newImage, $source, 0, 0, $start_width, $start_height, $newImageWidth, $newImageHeight, $width, $height); $ok = imagecopyresampled($newImage, $source, 0, 0, $start_width, $start_height, $newImageWidth, $newImageHeight, $width, $height);
switch ($imageType) { switch ($imageType) {
case "image/gif": case 'image/gif':
imagegif($newImage, $thumb_image_name); imagegif($newImage, $thumb_image_name);
break; break;
case "image/pjpeg": case 'image/pjpeg':
case "image/jpeg": case 'image/jpeg':
case "image/jpg": case 'image/jpg':
dump($thumb_image_name); dump($thumb_image_name);
imagejpeg($newImage, $thumb_image_name, 100); imagejpeg($newImage, $thumb_image_name, 100);
break; break;
case "image/png": case 'image/png':
case "image/x-png": case 'image/x-png':
imagepng($newImage, $thumb_image_name); imagepng($newImage, $thumb_image_name);
break; break;
} }
chmod($thumb_image_name, 0640); chmod($thumb_image_name, 0640);
return $thumb_image_name; return $thumb_image_name;
} }
} }

View File

@ -1,32 +1,31 @@
<?php <?php
namespace App\Controller; 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\Group as Entity;
use App\Entity\UserGroup; use App\Entity\UserGroup;
use App\Form\GroupType as Form; use App\Form\GroupType as Form;
use Doctrine\Persistence\ManagerRegistry;
use Ramsey\Uuid\Uuid;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class GroupController extends AbstractController class GroupController extends AbstractController
{ {
private $data="group"; private $data = 'group';
private $entity = "App\Entity\Group"; private $entity = "App\Entity\Group";
private $twig="Group/"; private $twig = 'Group/';
private $route="app_admin_group"; private $route = 'app_admin_group';
public function list($access): Response public function list($access): Response
{ {
return $this->render($this->twig.'list.html.twig', [ return $this->render($this->twig.'list.html.twig', [
"useheader"=>true, 'useheader' => true,
"usemenu"=>false, 'usemenu' => false,
"usesidebar"=>($access!="user"), 'usesidebar' => ('user' != $access),
"access"=>$access, 'access' => $access,
]); ]);
} }
@ -44,65 +43,64 @@ class GroupController extends AbstractController
// Nombre total d'enregistrement // Nombre total d'enregistrement
$qb = $em->getManager()->createQueryBuilder(); $qb = $em->getManager()->createQueryBuilder();
$qb->select('COUNT(entity)')->from($this->entity, 'entity')->getQuery()->getSingleScalarResult(); $qb->select('COUNT(entity)')->from($this->entity, 'entity')->getQuery()->getSingleScalarResult();
if($access=="user") { if ('user' == $access) {
$qb ->from("App:UserGroup","usergroup") $qb->from('App:UserGroup', 'usergroup')
->andWhere(("entity.isworkgroup=:flag")) ->andWhere('entity.isworkgroup=:flag')
->andWhere("entity.id=usergroup.group") ->andWhere('entity.id=usergroup.group')
->andWhere("usergroup.user=:user") ->andWhere('usergroup.user=:user')
->setParameter("flag", true) ->setParameter('flag', true)
->setParameter("user", $user); ->setParameter('user', $user);
} }
$total = $qb->getQuery()->getSingleScalarResult(); $total = $qb->getQuery()->getSingleScalarResult();
// Nombre d'enregistrement filtré // Nombre d'enregistrement filtré
if(!$search||$search["value"]=="") if (!$search || '' == $search['value']) {
$totalf = $total; $totalf = $total;
else { } else {
$qb = $em->getManager()->createQueryBuilder(); $qb = $em->getManager()->createQueryBuilder();
$qb->select('COUNT(entity)') $qb->select('COUNT(entity)')
->from($this->entity, 'entity') ->from($this->entity, 'entity')
->where('entity.label LIKE :value') ->where('entity.label LIKE :value')
->leftJoin('App:User', 'user', 'WITH', 'entity.owner = user.id AND user.username LIKE :value') ->leftJoin('App:User', 'user', 'WITH', 'entity.owner = user.id AND user.username LIKE :value')
->setParameter("value", "%".$search["value"]."%") ->setParameter('value', '%'.$search['value'].'%')
->getQuery() ->getQuery()
->getSingleScalarResult(); ->getSingleScalarResult();
if($access=="user") { if ('user' == $access) {
$qb ->from("App:UserGroup","usergroup") $qb->from('App:UserGroup', 'usergroup')
->andWhere(("entity.isworkgroup=:flag")) ->andWhere('entity.isworkgroup=:flag')
->andWhere("entity.id=usergroup.group") ->andWhere('entity.id=usergroup.group')
->andWhere("usergroup.user=:user") ->andWhere('usergroup.user=:user')
->setParameter("flag", true) ->setParameter('flag', true)
->setParameter("user", $user); ->setParameter('user', $user);
} }
$totalf = $qb->getQuery()->getSingleScalarResult(); $totalf = $qb->getQuery()->getSingleScalarResult();
} }
// Construction du tableau de retour // Construction du tableau de retour
$output = array( $output = [
'draw' => $draw, 'draw' => $draw,
'recordsFiltered' => $totalf, 'recordsFiltered' => $totalf,
'recordsTotal' => $total, 'recordsTotal' => $total,
'data' => array(), 'data' => [],
); ];
// Parcours des Enregistrement // Parcours des Enregistrement
$qb = $em->getManager()->createQueryBuilder(); $qb = $em->getManager()->createQueryBuilder();
$qb->select('entity') $qb->select('entity')
->from($this->entity, 'entity'); ->from($this->entity, 'entity');
if($access=="user") { if ('user' == $access) {
$qb ->from("App:UserGroup","usergroup") $qb->from('App:UserGroup', 'usergroup')
->andWhere(("entity.isworkgroup=:flag")) ->andWhere('entity.isworkgroup=:flag')
->andWhere("entity.id=usergroup.group") ->andWhere('entity.id=usergroup.group')
->andWhere("usergroup.user=:user") ->andWhere('usergroup.user=:user')
->setParameter("flag", true) ->setParameter('flag', true)
->setParameter("user", $user); ->setParameter('user', $user);
} }
if($search&&$search["value"]!="") { if ($search && '' != $search['value']) {
$qb->andWhere('entity.label LIKE :value') $qb->andWhere('entity.label LIKE :value')
->setParameter("value", "%".$search["value"]."%"); ->setParameter('value', '%'.$search['value'].'%');
} }
if ($ordercolumn) { if ($ordercolumn) {
@ -126,42 +124,48 @@ class GroupController extends AbstractController
foreach ($datas as $data) { foreach ($datas as $data) {
// Action // Action
$action = ""; $action = '';
switch ($access) { switch ($access) {
case "admin": case 'admin':
if($this->canupdate($access,$data,$em,false)) 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>"; $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)) 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>"; $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; break;
case "modo": case 'modo':
if($this->canupdate($access,$data,$em,false)) 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>"; $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)) 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>"; $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; break;
case "user": case 'user':
if($this->canupdate($access,$data,$em,false)) 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>"; $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>";
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 // 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))) 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>"; $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; break;
} }
$userinfo=""; $userinfo = '';
if ($data->getOwner()) { if ($data->getOwner()) {
$userinfo.="<img src='".$this->generateUrl('app_minio_image',["file"=>"avatar/".$data->getOwner()->getAvatar()])."' class='avatar'>"; $userinfo .= "<img src='".$this->generateUrl('app_minio_image', ['file' => 'avatar/'.$data->getOwner()->getAvatar()])."' class='avatar'>";
$userinfo.="<br>".$data->getOwner()->getUsername(); $userinfo .= '<br>'.$data->getOwner()->getUsername();
} }
$visitecpt = 0; $visitecpt = 0;
@ -171,27 +175,26 @@ class GroupController extends AbstractController
$visitelast = ($usergroup->getVisitedate() > $visitelast ? $usergroup->getVisitedate() : $visitelast); $visitelast = ($usergroup->getVisitedate() > $visitelast ? $usergroup->getVisitedate() : $visitelast);
} }
$tmp=array(); $tmp = [];
array_push($tmp, $action); array_push($tmp, $action);
array_push($tmp, $data->getLabel()); array_push($tmp, $data->getLabel());
array_push($tmp,($data->isIsworkgroup()?"oui":"non")); array_push($tmp, $data->isIsworkgroup() ? 'oui' : 'non');
array_push($tmp,($data->isIsopen()?"oui":"non")); array_push($tmp, $data->isIsopen() ? 'oui' : 'non');
array_push($tmp, $userinfo); array_push($tmp, $userinfo);
array_push($tmp,($visitelast?$visitelast->format("d/m/Y H:i")."<br>":"")."nb = ".$visitecpt); array_push($tmp, ($visitelast ? $visitelast->format('d/m/Y H:i').'<br>' : '').'nb = '.$visitecpt);
array_push($output["data"],$tmp); array_push($output['data'], $tmp);
} }
// Retour // Retour
return new JsonResponse($output); return new JsonResponse($output);
} }
public function submit($access, Request $request, ManagerRegistry $em): Response public function submit($access, Request $request, ManagerRegistry $em): Response
{ {
// Initialisation de l'enregistrement // Initialisation de l'enregistrement
$data = new Entity(); $data = new Entity();
$data->setApikey(Uuid::uuid4()); $data->setApikey(Uuid::uuid4());
if($access=="user") { if ('user' == $access) {
$data->setOwner($this->getUser()); $data->setOwner($this->getUser());
$data->setIsworkgroup(true); $data->setIsworkgroup(true);
} }
@ -200,11 +203,11 @@ class GroupController extends AbstractController
$this->cansubmit($access, $em); $this->cansubmit($access, $em);
// Création du formulaire // Création du formulaire
$form = $this->createForm(Form::class,$data,array( $form = $this->createForm(Form::class, $data, [
"mode"=>"submit", 'mode' => 'submit',
"appMasteridentity"=>$this->GetParameter("appMasteridentity"), 'appMasteridentity' => $this->GetParameter('appMasteridentity'),
"access"=>$access, 'access' => $access,
)); ]);
// Récupération des data du formulaire // Récupération des data du formulaire
$form->handleRequest($request); $form->handleRequest($request);
@ -214,26 +217,28 @@ class GroupController extends AbstractController
$data = $form->getData(); $data = $form->getData();
// Les groupes opé ne sont pas ouvert // Les groupes opé ne sont pas ouvert
if(!$data->isIsworkgroup()) $data->setIsopen(false); if (!$data->isIsworkgroup()) {
$data->setIsopen(false);
}
// Sauvegarde // Sauvegarde
$em->getManager()->persist($data); $em->getManager()->persist($data);
$em->getManager()->flush(); $em->getManager()->flush();
// Retour à la liste // Retour à la liste
return $this->redirectToRoute(str_replace("_admin_","_".$access."_",$this->route)); return $this->redirectToRoute(str_replace('_admin_', '_'.$access.'_', $this->route));
} }
// Affichage du formulaire // Affichage du formulaire
return $this->render($this->twig.'edit.html.twig', [ return $this->render($this->twig.'edit.html.twig', [
"useheader"=>true, 'useheader' => true,
"usemenu"=>false, 'usemenu' => false,
"usesidebar"=>($access!="user"), 'usesidebar' => ('user' != $access),
"mode"=>"submit", 'mode' => 'submit',
"access"=>$access, 'access' => $access,
"form"=>$form->createView(), 'form' => $form->createView(),
$this->data => $data, $this->data => $data,
"maxsize"=>($access=="user"?1200:null), 'maxsize' => ('user' == $access ? 1200 : null),
]); ]);
} }
@ -241,17 +246,19 @@ class GroupController extends AbstractController
{ {
// Initialisation de l'enregistrement // Initialisation de l'enregistrement
$data = $em->getRepository($this->entity)->find($id); $data = $em->getRepository($this->entity)->find($id);
if (!$data or $id<0) throw $this->createNotFoundException('Unable to find entity.'); if (!$data or $id < 0) {
throw $this->createNotFoundException('Unable to find entity.');
}
// Controler les permissions // Controler les permissions
$this->canupdate($access, $data, $em); $this->canupdate($access, $data, $em);
// Création du formulaire // Création du formulaire
$form = $this->createForm(Form::class,$data,array( $form = $this->createForm(Form::class, $data, [
"mode"=>"update", 'mode' => 'update',
"appMasteridentity"=>$this->GetParameter("appMasteridentity"), 'appMasteridentity' => $this->GetParameter('appMasteridentity'),
"access"=>$access, 'access' => $access,
)); ]);
// Récupération des data du formulaire // Récupération des data du formulaire
$form->handleRequest($request); $form->handleRequest($request);
@ -261,24 +268,26 @@ class GroupController extends AbstractController
$data = $form->getData(); $data = $form->getData();
// Les groupes opé ne sont pas ouvert // Les groupes opé ne sont pas ouvert
if(!$data->isIsworkgroup()) $data->setIsopen(false); if (!$data->isIsworkgroup()) {
$data->setIsopen(false);
}
$em->getManager()->flush(); $em->getManager()->flush();
// Retour à la liste // Retour à la liste
return $this->redirectToRoute(str_replace("_admin_","_".$access."_",$this->route)); return $this->redirectToRoute(str_replace('_admin_', '_'.$access.'_', $this->route));
} }
// Affichage du formulaire // Affichage du formulaire
return $this->render($this->twig.'edit.html.twig', [ return $this->render($this->twig.'edit.html.twig', [
"useheader" => true, 'useheader' => true,
"usemenu" => false, 'usemenu' => false,
"usesidebar" => ($access!="user"), 'usesidebar' => ('user' != $access),
$this->data => $data, $this->data => $data,
"mode" => "update", 'mode' => 'update',
"access"=>$access, 'access' => $access,
"form" => $form->createView(), 'form' => $form->createView(),
"maxsize"=>($access=="user"?1200:null), 'maxsize' => ('user' == $access ? 1200 : null),
]); ]);
} }
@ -286,7 +295,9 @@ class GroupController extends AbstractController
{ {
// Récupération de l'enregistrement courant // Récupération de l'enregistrement courant
$data = $em->getRepository($this->entity)->find($id); $data = $em->getRepository($this->entity)->find($id);
if (!$data) throw $this->createNotFoundException('Unable to find entity.'); if (!$data) {
throw $this->createNotFoundException('Unable to find entity.');
}
// Controler les permissions // Controler les permissions
$this->canupdate($access, $data, $em); $this->canupdate($access, $data, $em);
@ -295,22 +306,22 @@ class GroupController extends AbstractController
try { try {
$em->getManager()->remove($data); $em->getManager()->remove($data);
$em->getManager()->flush(); $em->getManager()->flush();
} } catch (\Exception $e) {
catch (\Exception $e) { $request->getSession()->getFlashBag()->add('error', $e->getMessage());
$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).'_update', ['id' => $id]);
} }
return $this->redirectToRoute(str_replace("_admin_","_".$access."_",$this->route)); return $this->redirectToRoute(str_replace('_admin_', '_'.$access.'_', $this->route));
} }
public function users($id, $access, Request $request, ManagerRegistry $em) public function users($id, $access, Request $request, ManagerRegistry $em)
{ {
// Récupération de l'enregistrement courant // Récupération de l'enregistrement courant
$data = $em->getRepository($this->entity)->find($id); $data = $em->getRepository($this->entity)->find($id);
if (!$data) throw $this->createNotFoundException('Unable to find entity.'); if (!$data) {
throw $this->createNotFoundException('Unable to find entity.');
}
// Controler les permissions // Controler les permissions
$this->canseemember($access, $data, $em); $this->canseemember($access, $data, $em);
@ -319,7 +330,7 @@ class GroupController extends AbstractController
return $this->render($this->twig.'users.html.twig', [ return $this->render($this->twig.'users.html.twig', [
'useheader' => true, 'useheader' => true,
'usemenu' => false, 'usemenu' => false,
'usesidebar' => ($access!="user"), 'usesidebar' => ('user' != $access),
'access' => $access, 'access' => $access,
$this->data => $data, $this->data => $data,
]); ]);
@ -329,14 +340,16 @@ class GroupController extends AbstractController
{ {
// Récupération de l'enregistrement courant // Récupération de l'enregistrement courant
$group = $em->getRepository($this->entity)->find($id); $group = $em->getRepository($this->entity)->find($id);
if (!$group) throw $this->createNotFoundException('Unable to find entity.'); if (!$group) {
throw $this->createNotFoundException('Unable to find entity.');
}
// Controler les permissions // Controler les permissions
$this->canseemember($access, $group, $em); $this->canseemember($access, $group, $em);
$sub = $em->getManager()->createQueryBuilder(); $sub = $em->getManager()->createQueryBuilder();
$sub->select("usergroup"); $sub->select('usergroup');
$sub->from("App:UserGroup","usergroup"); $sub->from('App:UserGroup', 'usergroup');
$sub->andWhere('usergroup.user = user.id'); $sub->andWhere('usergroup.user = user.id');
$sub->andWhere('usergroup.group = :groupid'); $sub->andWhere('usergroup.group = :groupid');
@ -354,41 +367,41 @@ class GroupController extends AbstractController
// Nombre total d'enregistrement // Nombre total d'enregistrement
$qb = $em->getManager()->createQueryBuilder(); $qb = $em->getManager()->createQueryBuilder();
switch ($access) { switch ($access) {
case "admin": case 'admin':
$qb->select('COUNT(user)') $qb->select('COUNT(user)')
->from('App:User', 'user') ->from('App:User', 'user')
->where($qb->expr()->not($qb->expr()->exists($sub->getDQL()))) ->where($qb->expr()->not($qb->expr()->exists($sub->getDQL())))
->setParameter("groupid",$id); ->setParameter('groupid', $id);
break; break;
case "modo": case 'modo':
$usermodo = $this->getUser()->getId(); $usermodo = $this->getUser()->getId();
$qb->select('COUNT(user)') $qb->select('COUNT(user)')
->from('App:User', 'user') ->from('App:User', 'user')
->from('App:UserModo', 'usermodo') ->from('App:UserModo', 'usermodo')
->where($qb->expr()->not($qb->expr()->exists($sub->getDQL()))) ->where($qb->expr()->not($qb->expr()->exists($sub->getDQL())))
->andWhere("usermodo.niveau01 = user.niveau01") ->andWhere('usermodo.niveau01 = user.niveau01')
->andWhere("usermodo.user = :userid") ->andWhere('usermodo.user = :userid')
->setParameter("userid", $usermodo) ->setParameter('userid', $usermodo)
->setParameter("groupid",$id); ->setParameter('groupid', $id);
break; break;
case "user": case 'user':
$niveau01 = $this->getUser()->getNiveau01(); $niveau01 = $this->getUser()->getNiveau01();
$niveau02 = $this->getUser()->getNiveau02(); $niveau02 = $this->getUser()->getNiveau02();
$qb->select('COUNT(user)') $qb->select('COUNT(user)')
->from('App:User', 'user') ->from('App:User', 'user')
->where($qb->expr()->not($qb->expr()->exists($sub->getDQL()))) ->where($qb->expr()->not($qb->expr()->exists($sub->getDQL())))
->setParameter("groupid",$id); ->setParameter('groupid', $id);
switch($request->getSession()->get("scopeannu")) { switch ($request->getSession()->get('scopeannu')) {
case "SAME_NIVEAU01": case 'SAME_NIVEAU01':
$qb->andWhere("user.niveau01 = :niveau01")->setParameter("niveau01",$niveau01); $qb->andWhere('user.niveau01 = :niveau01')->setParameter('niveau01', $niveau01);
break; break;
case "SAME_NIVEAU02": case 'SAME_NIVEAU02':
$qb->andWhere("user.niveau02 = :niveau02")->setParameter("niveau02",$niveau02); $qb->andWhere('user.niveau02 = :niveau02')->setParameter('niveau02', $niveau02);
break; break;
} }
break; break;
@ -397,54 +410,54 @@ class GroupController extends AbstractController
$totalf = null; $totalf = null;
// Nombre d'enregistrement filtré // Nombre d'enregistrement filtré
if($search["value"]=="") if ('' == $search['value']) {
$totalf = $total; $totalf = $total;
else { } else {
switch ($access) { switch ($access) {
case "admin": case 'admin':
$totalf = $em->getManager()->createQueryBuilder() $totalf = $em->getManager()->createQueryBuilder()
->select('COUNT(user)') ->select('COUNT(user)')
->from('App:User', 'user') ->from('App:User', 'user')
->where('user.username LIKE :value OR user.email LIKE :value') ->where('user.username LIKE :value OR user.email LIKE :value')
->andWhere($qb->expr()->not($qb->expr()->exists($sub->getDQL()))) ->andWhere($qb->expr()->not($qb->expr()->exists($sub->getDQL())))
->setParameter("value", "%".$search["value"]."%") ->setParameter('value', '%'.$search['value'].'%')
->setParameter("groupid",$id) ->setParameter('groupid', $id)
->getQuery() ->getQuery()
->getSingleScalarResult(); ->getSingleScalarResult();
break; break;
case "modo": case 'modo':
$totalf = $em->getManager()->createQueryBuilder() $totalf = $em->getManager()->createQueryBuilder()
->select('COUNT(user)') ->select('COUNT(user)')
->from('App:User', 'user') ->from('App:User', 'user')
->from('App:UserModo', 'usermodo') ->from('App:UserModo', 'usermodo')
->where('user.username LIKE :value OR user.email LIKE :value') ->where('user.username LIKE :value OR user.email LIKE :value')
->andWhere($qb->expr()->not($qb->expr()->exists($sub->getDQL()))) ->andWhere($qb->expr()->not($qb->expr()->exists($sub->getDQL())))
->andWhere("usermodo.niveau01 = user.niveau01") ->andWhere('usermodo.niveau01 = user.niveau01')
->andWhere("usermodo.user = :userid") ->andWhere('usermodo.user = :userid')
->setParameter("userid", $usermodo) ->setParameter('userid', $usermodo)
->setParameter("value", "%".$search["value"]."%") ->setParameter('value', '%'.$search['value'].'%')
->setParameter("groupid",$id) ->setParameter('groupid', $id)
->getQuery() ->getQuery()
->getSingleScalarResult(); ->getSingleScalarResult();
break; break;
case "user": case 'user':
$qb = $em->getManager()->createQueryBuilder() $qb = $em->getManager()->createQueryBuilder()
->select('COUNT(user)') ->select('COUNT(user)')
->from('App:User', 'user') ->from('App:User', 'user')
->where('user.username LIKE :value OR user.email LIKE :value') ->where('user.username LIKE :value OR user.email LIKE :value')
->andWhere($qb->expr()->not($qb->expr()->exists($sub->getDQL()))) ->andWhere($qb->expr()->not($qb->expr()->exists($sub->getDQL())))
->setParameter("value", "%".$search["value"]."%") ->setParameter('value', '%'.$search['value'].'%')
->setParameter("groupid",$id); ->setParameter('groupid', $id);
switch($request->getSession()->get("scopeannu")) { switch ($request->getSession()->get('scopeannu')) {
case "SAME_NIVEAU01": case 'SAME_NIVEAU01':
$qb->andWhere("user.niveau01 = :niveau01")->setParameter("niveau01",$niveau01); $qb->andWhere('user.niveau01 = :niveau01')->setParameter('niveau01', $niveau01);
break; break;
case "SAME_NIVEAU02": case 'SAME_NIVEAU02':
$qb->andWhere("user.niveau02 = :niveau02")->setParameter("niveau02",$niveau02); $qb->andWhere('user.niveau02 = :niveau02')->setParameter('niveau02', $niveau02);
break; break;
} }
@ -454,49 +467,49 @@ class GroupController extends AbstractController
} }
// Construction du tableau de retour // Construction du tableau de retour
$output = array( $output = [
'draw' => $draw, 'draw' => $draw,
'recordsFiltered' => $totalf, 'recordsFiltered' => $totalf,
'recordsTotal' => $total, 'recordsTotal' => $total,
'data' => array(), 'data' => [],
); ];
// Parcours des Enregistrement // Parcours des Enregistrement
$qb = $em->getManager()->createQueryBuilder(); $qb = $em->getManager()->createQueryBuilder();
$qb->select('user')->from("App:User",'user'); $qb->select('user')->from('App:User', 'user');
switch ($access) { switch ($access) {
case "admin": case 'admin':
$qb->where($qb->expr()->not($qb->expr()->exists($sub->getDQL()))); $qb->where($qb->expr()->not($qb->expr()->exists($sub->getDQL())));
break; break;
case "modo": case 'modo':
$qb->from('App:UserModo', 'usermodo') $qb->from('App:UserModo', 'usermodo')
->where($qb->expr()->not($qb->expr()->exists($sub->getDQL()))) ->where($qb->expr()->not($qb->expr()->exists($sub->getDQL())))
->andWhere("usermodo.niveau01 = user.niveau01") ->andWhere('usermodo.niveau01 = user.niveau01')
->andWhere("usermodo.user = :userid") ->andWhere('usermodo.user = :userid')
->setParameter("userid", $usermodo); ->setParameter('userid', $usermodo);
break; break;
case "user": case 'user':
$qb->where($qb->expr()->not($qb->expr()->exists($sub->getDQL()))); $qb->where($qb->expr()->not($qb->expr()->exists($sub->getDQL())));
switch($request->getSession()->get("scopeannu")) { switch ($request->getSession()->get('scopeannu')) {
case "SAME_NIVEAU01": case 'SAME_NIVEAU01':
$qb->andWhere("user.niveau01 = :niveau01")->setParameter("niveau01",$niveau01); $qb->andWhere('user.niveau01 = :niveau01')->setParameter('niveau01', $niveau01);
break; break;
case "SAME_NIVEAU02": case 'SAME_NIVEAU02':
$qb->andWhere("user.niveau02 = :niveau02")->setParameter("niveau02",$niveau02); $qb->andWhere('user.niveau02 = :niveau02')->setParameter('niveau02', $niveau02);
break; break;
} }
break; break;
} }
if($search["value"]!="") { if ('' != $search['value']) {
$qb->andWhere('user.username LIKE :value OR user.email LIKE :value') $qb->andWhere('user.username LIKE :value OR user.email LIKE :value')
->setParameter("value", "%".$search["value"]."%"); ->setParameter('value', '%'.$search['value'].'%');
} }
$qb->setParameter("groupid",$id); $qb->setParameter('groupid', $id);
switch ($ordercolumn) { switch ($ordercolumn) {
case 2: case 2:
$qb->orderBy('user.username', $orderdir); $qb->orderBy('user.username', $orderdir);
@ -512,33 +525,35 @@ class GroupController extends AbstractController
foreach ($datas as $data) { foreach ($datas as $data) {
// Action // Action
$action = ""; $action = '';
if($canupdatemember) if ($canupdatemember) {
$action .= "<a style='cursor:pointer' onClick='addUsers(".$data->getId().")'><i class='fa fa-plus fa-fw'></i></a>"; $action .= "<a style='cursor:pointer' onClick='addUsers(".$data->getId().")'><i class='fa fa-plus fa-fw'></i></a>";
}
// Avatar // Avatar
$avatar="<img src='".$this->generateUrl('app_minio_image',["file"=>"avatar/".$data->getAvatar()])."' class='avatar'>"; $avatar = "<img src='".$this->generateUrl('app_minio_image', ['file' => 'avatar/'.$data->getAvatar()])."' class='avatar'>";
array_push($output["data"],array("DT_RowId"=>"user".$data->getId(),$action,$avatar,$data->getUsername(),$data->getEmail(),"","")); array_push($output['data'], ['DT_RowId' => 'user'.$data->getId(), $action, $avatar, $data->getUsername(), $data->getEmail(), '', '']);
} }
// Retour // Retour
return new JsonResponse($output); return new JsonResponse($output);
} }
public function usersin($id, $access, Request $request, ManagerRegistry $em) public function usersin($id, $access, Request $request, ManagerRegistry $em)
{ {
// Récupération de l'enregistrement courant // Récupération de l'enregistrement courant
$group = $em->getRepository($this->entity)->find($id); $group = $em->getRepository($this->entity)->find($id);
if (!$group) throw $this->createNotFoundException('Unable to find entity.'); if (!$group) {
throw $this->createNotFoundException('Unable to find entity.');
}
// Controler les permissions // Controler les permissions
$this->canseemember($access, $group, $em); $this->canseemember($access, $group, $em);
$sub = $em->getManager()->createQueryBuilder(); $sub = $em->getManager()->createQueryBuilder();
$sub->select("usergroup"); $sub->select('usergroup');
$sub->from("App:UserGroup","usergroup"); $sub->from('App:UserGroup', 'usergroup');
$sub->andWhere('usergroup.user = user.id'); $sub->andWhere('usergroup.user = user.id');
$sub->andWhere('usergroup.group = :groupid'); $sub->andWhere('usergroup.group = :groupid');
@ -553,81 +568,82 @@ class GroupController extends AbstractController
// Nombre total d'enregistrement // Nombre total d'enregistrement
$qb = $em->getManager()->createQueryBuilder(); $qb = $em->getManager()->createQueryBuilder();
if($access=="admin"||$access=="user") if ('admin' == $access || 'user' == $access) {
$qb->select('COUNT(user)') $qb->select('COUNT(user)')
->from('App:User', 'user') ->from('App:User', 'user')
->where($qb->expr()->exists($sub->getDQL())) ->where($qb->expr()->exists($sub->getDQL()))
->setParameter("groupid",$id); ->setParameter('groupid', $id);
else { } else {
$usermodo = $this->getUser()->getId(); $usermodo = $this->getUser()->getId();
$qb->select('COUNT(user)') $qb->select('COUNT(user)')
->from('App:User', 'user') ->from('App:User', 'user')
->from('App:UserModo', 'usermodo') ->from('App:UserModo', 'usermodo')
->where($qb->expr()->exists($sub->getDQL())) ->where($qb->expr()->exists($sub->getDQL()))
->andWhere("usermodo.niveau01 = user.niveau01") ->andWhere('usermodo.niveau01 = user.niveau01')
->andWhere("usermodo.user = :userid") ->andWhere('usermodo.user = :userid')
->setParameter("userid", $usermodo) ->setParameter('userid', $usermodo)
->setParameter("groupid",$id); ->setParameter('groupid', $id);
} }
$total = $qb->getQuery()->getSingleScalarResult(); $total = $qb->getQuery()->getSingleScalarResult();
// Nombre d'enregistrement filtré // Nombre d'enregistrement filtré
if($search["value"]=="") if ('' == $search['value']) {
$totalf = $total; $totalf = $total;
else { } else {
if($access=="admin"||$access=="user") if ('admin' == $access || 'user' == $access) {
$totalf = $em->getManager()->createQueryBuilder() $totalf = $em->getManager()->createQueryBuilder()
->select('COUNT(user)') ->select('COUNT(user)')
->from('App:User', 'user') ->from('App:User', 'user')
->where('user.username LIKE :value OR user.email LIKE :value') ->where('user.username LIKE :value OR user.email LIKE :value')
->andWhere($qb->expr()->exists($sub->getDQL())) ->andWhere($qb->expr()->exists($sub->getDQL()))
->setParameter("value", "%".$search["value"]."%") ->setParameter('value', '%'.$search['value'].'%')
->setParameter("groupid",$id) ->setParameter('groupid', $id)
->getQuery() ->getQuery()
->getSingleScalarResult(); ->getSingleScalarResult();
else } else {
$totalf = $em->getManager()->createQueryBuilder() $totalf = $em->getManager()->createQueryBuilder()
->select('COUNT(user)') ->select('COUNT(user)')
->from('App:User', 'user') ->from('App:User', 'user')
->from('App:UserModo', 'usermodo') ->from('App:UserModo', 'usermodo')
->where('user.username LIKE :value OR user.email LIKE :value') ->where('user.username LIKE :value OR user.email LIKE :value')
->andWhere($qb->expr()->exists($sub->getDQL())) ->andWhere($qb->expr()->exists($sub->getDQL()))
->andWhere("usermodo.niveau01 = user.niveau01") ->andWhere('usermodo.niveau01 = user.niveau01')
->andWhere("usermodo.user = :userid") ->andWhere('usermodo.user = :userid')
->setParameter("userid", $usermodo) ->setParameter('userid', $usermodo)
->setParameter("value", "%".$search["value"]."%") ->setParameter('value', '%'.$search['value'].'%')
->setParameter("groupid",$id) ->setParameter('groupid', $id)
->getQuery() ->getQuery()
->getSingleScalarResult(); ->getSingleScalarResult();
}
} }
// Construction du tableau de retour // Construction du tableau de retour
$output = array( $output = [
'draw' => $draw, 'draw' => $draw,
'recordsFiltered' => $totalf, 'recordsFiltered' => $totalf,
'recordsTotal' => $total, 'recordsTotal' => $total,
'data' => array(), 'data' => [],
); ];
// Parcours des Enregistrement // Parcours des Enregistrement
$qb = $em->getManager()->createQueryBuilder(); $qb = $em->getManager()->createQueryBuilder();
$qb->select('user')->from("App:User",'user'); $qb->select('user')->from('App:User', 'user');
if($access=="admin"||$access=="user") if ('admin' == $access || 'user' == $access) {
$qb->where($qb->expr()->exists($sub->getDQL())); $qb->where($qb->expr()->exists($sub->getDQL()));
else } else {
$qb->from('App:UserModo', 'usermodo') $qb->from('App:UserModo', 'usermodo')
->where($qb->expr()->exists($sub->getDQL())) ->where($qb->expr()->exists($sub->getDQL()))
->andWhere("usermodo.niveau01 = user.niveau01") ->andWhere('usermodo.niveau01 = user.niveau01')
->andWhere("usermodo.user = :userid") ->andWhere('usermodo.user = :userid')
->setParameter("userid", $usermodo); ->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);
if ('' != $search['value']) {
$qb->andWhere('user.username LIKE :value OR user.email LIKE :value')
->setParameter('value', '%'.$search['value'].'%');
}
$qb->setParameter('groupid', $id);
switch ($ordercolumn) { switch ($ordercolumn) {
case 2: case 2:
$qb->orderBy('user.username', $orderdir); $qb->orderBy('user.username', $orderdir);
@ -642,32 +658,35 @@ class GroupController extends AbstractController
foreach ($datas as $data) { foreach ($datas as $data) {
// Propriétaire // Propriétaire
$usergroup=$em->getRepository("App\Entity\UserGroup")->findOneBy(["user"=>$data->getId(),"group"=>$id]); $usergroup = $em->getRepository("App\Entity\UserGroup")->findOneBy(['user' => $data->getId(), 'group' => $id]);
$fgproprio = ($usergroup->getUser() == $group->getOwner()); $fgproprio = ($usergroup->getUser() == $group->getOwner());
$fgme=($usergroup->getUser()==$this->getUser()&&$access!="admin"); $fgme = ($usergroup->getUser() == $this->getUser() && 'admin' != $access);
// Action // Action
$action = ""; $action = '';
if($this->canupdatemember($access,$group,$em,false)&&!$fgproprio&&!$fgme) 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>"; $action .= "<a style='cursor:pointer' onClick='delUsers(".$data->getId().")'><i class='fa fa-minus fa-fw'></i></a>";
}
// Avatar // Avatar
$avatar="<img src='".$this->generateUrl('app_minio_image',["file"=>"avatar/".$data->getAvatar()])."' class='avatar'>"; $avatar = "<img src='".$this->generateUrl('app_minio_image', ['file' => 'avatar/'.$data->getAvatar()])."' class='avatar'>";
// Flag manager // Flag manager
$rolegroup=""; $rolegroup = '';
if($fgproprio) $rolegroup="Propriétaire du groupe"; if ($fgproprio) {
elseif($this->canupdatemember($access,$group,$em,false)&&!$fgme) { $rolegroup = 'Propriétaire du groupe';
$selectuser=($usergroup->getRolegroup()==0?"selected='selected'":""); } elseif ($this->canupdatemember($access, $group, $em, false) && !$fgme) {
$selectwritter=($usergroup->getRolegroup()==50?"selected='selected'":""); $selectuser = (0 == $usergroup->getRolegroup() ? "selected='selected'" : '');
$selectmanager=($usergroup->getRolegroup()==90?"selected='selected'":""); $selectwritter = (50 == $usergroup->getRolegroup() ? "selected='selected'" : '');
$selectmanager = (90 == $usergroup->getRolegroup() ? "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>'; $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 = (0 == $usergroup->getRolegroup() ? 'Utilisateur' : (50 == $usergroup->getRolegroup() ? 'Collaborateur' : 'Gestionnaire'));
} }
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); $tmp = ['DT_RowId' => 'user'.$data->getId(), $action, $avatar, $data->getUsername(), $data->getEmail(), $rolegroup];
array_push($output["data"],$tmp); array_push($output['data'], $tmp);
} }
// Retour // Retour
@ -678,16 +697,22 @@ class GroupController extends AbstractController
{ {
// Récupération de l'enregistrement courant // Récupération de l'enregistrement courant
$group = $em->getRepository($this->entity)->find($groupid); $group = $em->getRepository($this->entity)->find($groupid);
if (!$group) throw $this->createNotFoundException('Unable to find entity.'); if (!$group) {
throw $this->createNotFoundException('Unable to find entity.');
}
$user = $em->getRepository("App\Entity\User")->find($userid); $user = $em->getRepository("App\Entity\User")->find($userid);
if (!$user) throw $this->createNotFoundException('Unable to find entity.'); if (!$user) {
throw $this->createNotFoundException('Unable to find entity.');
}
$output=array(); $output = [];
$this->canupdatemember($access, $group, $em, true); $this->canupdatemember($access, $group, $em, true);
$usergroup = $em->getRepository("App\Entity\UserGroup")->findOneBy(array("user"=>$user,"group"=>$group)); $usergroup = $em->getRepository("App\Entity\UserGroup")->findOneBy(['user' => $user, 'group' => $group]);
if($usergroup) return new JsonResponse($output); if ($usergroup) {
return new JsonResponse($output);
}
$usergroup = new UserGroup(); $usergroup = new UserGroup();
$usergroup->setUser($user); $usergroup->setUser($user);
@ -705,16 +730,22 @@ class GroupController extends AbstractController
{ {
// Récupération de l'enregistrement courant // Récupération de l'enregistrement courant
$group = $em->getRepository($this->entity)->find($groupid); $group = $em->getRepository($this->entity)->find($groupid);
if (!$group) throw $this->createNotFoundException('Unable to find entity.'); if (!$group) {
throw $this->createNotFoundException('Unable to find entity.');
}
$user = $em->getRepository("App\Entity\User")->find($userid); $user = $em->getRepository("App\Entity\User")->find($userid);
if (!$user) throw $this->createNotFoundException('Unable to find entity.'); if (!$user) {
throw $this->createNotFoundException('Unable to find entity.');
}
$output=array(); $output = [];
$this->canupdatemember($access, $group, $em, true); $this->canupdatemember($access, $group, $em, true);
if($user==$group->getOwner()) throw $this->createAccessDeniedException('Permission denied'); if ($user == $group->getOwner()) {
throw $this->createAccessDeniedException('Permission denied');
}
$usergroup = $em->getRepository("App\Entity\UserGroup")->findOneBy(array("user"=>$user,"group"=>$group)); $usergroup = $em->getRepository("App\Entity\UserGroup")->findOneBy(['user' => $user, 'group' => $group]);
if ($usergroup) { if ($usergroup) {
$em->getManager()->remove($usergroup); $em->getManager()->remove($usergroup);
$em->getManager()->flush(); $em->getManager()->flush();
@ -728,17 +759,22 @@ class GroupController extends AbstractController
{ {
// Récupération de l'enregistrement courant // Récupération de l'enregistrement courant
$group = $em->getRepository($this->entity)->find($groupid); $group = $em->getRepository($this->entity)->find($groupid);
if (!$group) throw $this->createNotFoundException('Unable to find entity.'); if (!$group) {
throw $this->createNotFoundException('Unable to find entity.');
}
$user = $em->getRepository("App\Entity\User")->find($userid); $user = $em->getRepository("App\Entity\User")->find($userid);
if (!$user) throw $this->createNotFoundException('Unable to find entity.'); if (!$user) {
throw $this->createNotFoundException('Unable to find entity.');
}
$output=array(); $output = [];
$this->canupdatemember($access, $group, $em, true); $this->canupdatemember($access, $group, $em, true);
if($user==$group->getOwner()) throw $this->createAccessDeniedException('Permission denied'); if ($user == $group->getOwner()) {
throw $this->createAccessDeniedException('Permission denied');
}
$usergroup = $em->getRepository("App\Entity\UserGroup")->findOneBy(['user' => $user, 'group' => $group]);
$usergroup = $em->getRepository("App\Entity\UserGroup")->findOneBy(array("user"=>$user,"group"=>$group));
if ($usergroup) { if ($usergroup) {
$usergroup->setRolegroup($roleid); $usergroup->setRolegroup($roleid);
$em->getManager()->persist($usergroup); $em->getManager()->persist($usergroup);
@ -753,71 +789,101 @@ class GroupController extends AbstractController
{ {
// Récupération de l'enregistrement courant // Récupération de l'enregistrement courant
$group = $em->getRepository($this->entity)->find($id); $group = $em->getRepository($this->entity)->find($id);
if (!$group) throw $this->createNotFoundException('Unable to find entity.'); 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 // 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))) { 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)); $usergroup = $em->getRepository("App\Entity\UserGroup")->findOneBy(['user' => $this->getUser(), 'group' => $group]);
if ($usergroup) { if ($usergroup) {
$em->getManager()->remove($usergroup); $em->getManager()->remove($usergroup);
$em->getManager()->flush(); $em->getManager()->flush();
} }
} }
return $this->redirectToRoute(str_replace("_admin_","_".$access."_",$this->route)); return $this->redirectToRoute(str_replace('_admin_', '_'.$access.'_', $this->route));
} }
private function cansubmit($access,$em) { private function cansubmit($access, $em)
{
switch ($access) { switch ($access) {
case "admin" : return true; break; case 'admin': return true;
case "user" : return true; break; break;
case 'user': return true;
break;
} }
throw $this->createAccessDeniedException('Permission denied'); throw $this->createAccessDeniedException('Permission denied');
} }
private function canupdate($access, $entity, $em, $fgblock = true)
private function canupdate($access,$entity,$em,$fgblock=true) { {
$toreturn = false; $toreturn = false;
switch ($access) { switch ($access) {
case "admin" : $toreturn=($entity->getId()>0); break; case 'admin': $toreturn = ($entity->getId() > 0);
case "user": break;
if(!$entity->isIsworkgroup()||$entity->getOwner()!=$this->getUser()) $toreturn=false; case 'user':
else $toreturn=true; if (!$entity->isIsworkgroup() || $entity->getOwner() != $this->getUser()) {
$toreturn = false;
} else {
$toreturn = true;
}
break; break;
} }
if($fgblock&&!$toreturn) throw $this->createAccessDeniedException('Permission denied'); if ($fgblock && !$toreturn) {
throw $this->createAccessDeniedException('Permission denied');
}
return $toreturn; return $toreturn;
} }
private function canseemember($access,$entity,$em,$fgblock=true) { private function canseemember($access, $entity, $em, $fgblock = true)
{
$toreturn = false; $toreturn = false;
switch ($access) { switch ($access) {
case "admin" : $toreturn=($entity->getId()>0); break; case 'admin': $toreturn = ($entity->getId() > 0);
case "modo" : $toreturn=($entity->getId()>0); break; break;
case "user": case 'modo': $toreturn = ($entity->getId() > 0);
$usergroup=$em->getRepository("App\Entity\UserGroup")->findOneBy(["user"=>$this->getUser(),"group"=>$entity]); break;
if(!$usergroup||!$entity->isIsworkgroup()||$entity->getId()<0) $toreturn=false; case 'user':
else $toreturn=true; $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; break;
} }
if($fgblock&&!$toreturn) throw $this->createAccessDeniedException('Permission denied'); if ($fgblock && !$toreturn) {
throw $this->createAccessDeniedException('Permission denied');
}
return $toreturn; return $toreturn;
} }
private function canupdatemember($access, $entity, $em, $fgblock = true)
private function canupdatemember($access,$entity,$em,$fgblock=true) { {
$toreturn = false; $toreturn = false;
switch ($access) { switch ($access) {
case "admin" : $toreturn=($entity->getId()>0&&!$entity->getLdapfilter()); break; case 'admin': $toreturn = ($entity->getId() > 0 && !$entity->getLdapfilter());
case "modo" : $toreturn=($entity->getId()>0); break; break;
case "user": case 'modo': $toreturn = ($entity->getId() > 0);
$usergroup=$em->getRepository("App\Entity\UserGroup")->findOneBy(["user"=>$this->getUser(),"group"=>$entity]); break;
if(!$usergroup||!$entity->isIsworkgroup()||$entity->getId()<0) $toreturn=false; case 'user':
elseif($usergroup->getRolegroup()<90) $toreturn=false; $usergroup = $em->getRepository("App\Entity\UserGroup")->findOneBy(['user' => $this->getUser(), 'group' => $entity]);
else $toreturn=true; if (!$usergroup || !$entity->isIsworkgroup() || $entity->getId() < 0) {
$toreturn = false;
} elseif ($usergroup->getRolegroup() < 90) {
$toreturn = false;
} else {
$toreturn = true;
}
break; break;
} }
if($fgblock&&!$toreturn) throw $this->createAccessDeniedException('Permission denied'); if ($fgblock && !$toreturn) {
throw $this->createAccessDeniedException('Permission denied');
}
return $toreturn; return $toreturn;
} }
} }

View File

@ -1,57 +1,53 @@
<?php <?php
namespace App\Controller; namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Response;
class HomeController extends AbstractController class HomeController extends AbstractController
{ {
public function home(Request $request): Response public function home(Request $request): Response
{ {
if($request->getSession()->get("fgforceconnect")) if ($request->getSession()->get('fgforceconnect')) {
return $this->redirectToRoute("app_user_home"); return $this->redirectToRoute('app_user_home');
}
return $this->render('Home/home.html.twig', [ return $this->render('Home/home.html.twig', [
"useheader"=>true, 'useheader' => true,
"usemenu"=>true, 'usemenu' => true,
"usesidebar"=>false, 'usesidebar' => false,
"maxsize"=>1000, 'maxsize' => 1000,
]); ]);
} }
public function homeuser($access): Response public function homeuser($access): Response
{ {
return $this->render('Home/home.html.twig', [ return $this->render('Home/home.html.twig', [
"useheader"=>true, 'useheader' => true,
"usemenu"=>false, 'usemenu' => false,
"usesidebar"=>false, 'usesidebar' => false,
"maxsize"=>1000, 'maxsize' => 1000,
]); ]);
} }
public function homeadmin($access): Response public function homeadmin($access): Response
{ {
return $this->redirectToRoute("app_admin_config"); return $this->redirectToRoute('app_admin_config');
} }
public function homemodo($access): Response public function homemodo($access): Response
{ {
return $this->redirectToRoute("app_modo_niveau02"); return $this->redirectToRoute('app_modo_niveau02');
} }
public function docrest(): Response public function docrest(): Response
{ {
return $this->render('Home/docrest.html.twig', [ return $this->render('Home/docrest.html.twig', [
"useheader"=>true, 'useheader' => true,
"usemenu"=>false, 'usemenu' => false,
"usesidebar"=>true, 'usesidebar' => true,
]); ]);
} }
} }

View File

@ -1,22 +1,19 @@
<?php <?php
namespace App\Controller; namespace App\Controller;
use App\Form\LoginType;
use App\Service\ApiService;
use App\Service\LdapService;
use App\Service\PasswordEncoder;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Exception\BadRequestException;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Exception\BadRequestException;
use Doctrine\Persistence\ManagerRegistry;
use App\Service\ApiService;
use App\Service\PasswordEncoder;
use App\Service\LdapService;
use App\Form\LoginType;
class HydraController extends AbstractController class HydraController extends AbstractController
{ {
private $apiservice; private $apiservice;
private $passwordencoder; private $passwordencoder;
private $ldapservice; private $ldapservice;
@ -30,7 +27,6 @@ class HydraController extends AbstractController
public function loginsql(Request $request): Response public function loginsql(Request $request): Response
{ {
$challenge = $request->query->get('login_challenge'); $challenge = $request->query->get('login_challenge');
// S'il n'y a pas de challenge, on déclenche une bad request // S'il n'y a pas de challenge, on déclenche une bad request
@ -39,9 +35,10 @@ class HydraController extends AbstractController
} }
// On vérifie que la requête d'identification provient bien de hydra // On vérifie que la requête d'identification provient bien de hydra
$response = $this->apiservice->run("GET",$this->getParameter('hydraLoginchallenge').$challenge,null); $response = $this->apiservice->run('GET', $this->getParameter('hydraLoginchallenge').$challenge, null);
if(!$response) if (!$response) {
throw new BadRequestException('challenge invalide'); throw new BadRequestException('challenge invalide');
}
// si le challenge est validé par hydra, on le stocke en session pour l'utiliser par la suite et on redirige vers une route interne protégée qui va déclencher l'identification FranceConnect // si le challenge est validé par hydra, on le stocke en session pour l'utiliser par la suite et on redirige vers une route interne protégée qui va déclencher l'identification FranceConnect
$request->getSession()->set('hydraChallenge', $challenge); $request->getSession()->set('hydraChallenge', $challenge);
@ -52,48 +49,52 @@ class HydraController extends AbstractController
// Récupération des data du formulaire // Récupération des data du formulaire
$form->handleRequest($request); $form->handleRequest($request);
// Affichage du formulaire // Affichage du formulaire
return $this->render("Home/loginHYDRA.html.twig", [ return $this->render('Home/loginHYDRA.html.twig', [
"useheader"=>false, 'useheader' => false,
"usemenu"=>false, 'usemenu' => false,
"usesidebar"=>false, 'usesidebar' => false,
"form"=>$form->createView(), 'form' => $form->createView(),
"mode"=>"SQL", 'mode' => 'SQL',
]); ]);
} }
public function checkloginsql(Request $request,ManagerRegistry $em) { public function checkloginsql(Request $request, ManagerRegistry $em)
$username=$request->get('login')["username"]; {
$password=$request->get('login')["password"]; $username = $request->get('login')['username'];
$password = $request->get('login')['password'];
// user exist ? // user exist ?
$user=$em->getRepository("App\Entity\User")->findOneBy(["username"=>$username]); $user = $em->getRepository("App\Entity\User")->findOneBy(['username' => $username]);
if(!$user) return $this->redirect($this->generateUrl('app_hydra_loginsql',["login_challenge"=>$request->getSession()->get("hydraChallenge")])); if (!$user) {
return $this->redirect($this->generateUrl('app_hydra_loginsql', ['login_challenge' => $request->getSession()->get('hydraChallenge')]));
}
$islogin = $this->passwordencoder->verify($user->getPassword(), $password, $user->getSalt()); $islogin = $this->passwordencoder->verify($user->getPassword(), $password, $user->getSalt());
if(!$islogin) return $this->redirect($this->generateUrl('app_hydra_loginsql',["login_challenge"=>$request->getSession()->get("hydraChallenge")])); if (!$islogin) {
return $this->redirect($this->generateUrl('app_hydra_loginsql', ['login_challenge' => $request->getSession()->get('hydraChallenge')]));
}
$response = $this->apiservice->run("PUT",$this->getParameter('hydraLoginchallengeaccept').$request->getSession()->get('hydraChallenge'),["subject"=>$user->getEmail(),"acr"=>"string"]); $response = $this->apiservice->run('PUT', $this->getParameter('hydraLoginchallengeaccept').$request->getSession()->get('hydraChallenge'), ['subject' => $user->getEmail(), 'acr' => 'string']);
if(!$response||$response->code!="200") if (!$response || '200' != $response->code) {
throw new BadRequestException('login accept invalide'); throw new BadRequestException('login accept invalide');
}
$datas = [ $datas = [
"username"=>$user->getUsername(), 'username' => $user->getUsername(),
"email"=>$user->getEmail(), 'email' => $user->getEmail(),
"firstname"=>$user->getFirstname(), 'firstname' => $user->getFirstname(),
"lastname"=>$user->getLastname() 'lastname' => $user->getLastname(),
]; ];
$request->getSession()->set("datas",$datas); $request->getSession()->set('datas', $datas);
$redirect = $response->body->redirect_to; $redirect = $response->body->redirect_to;
return $this->redirect($redirect, 301);
return $this->redirect($redirect, 301);
} }
public function loginldap(Request $request): Response public function loginldap(Request $request): Response
{ {
$challenge = $request->query->get('login_challenge'); $challenge = $request->query->get('login_challenge');
// S'il n'y a pas de challenge, on déclenche une bad request // S'il n'y a pas de challenge, on déclenche une bad request
@ -102,9 +103,10 @@ class HydraController extends AbstractController
} }
// On vérifie que la requête d'identification provient bien de hydra // On vérifie que la requête d'identification provient bien de hydra
$response = $this->apiservice->run("GET",$this->getParameter('hydraLoginchallenge').$challenge,null); $response = $this->apiservice->run('GET', $this->getParameter('hydraLoginchallenge').$challenge, null);
if(!$response) if (!$response) {
throw new BadRequestException('challenge invalide'); throw new BadRequestException('challenge invalide');
}
// si le challenge est validé par hydra, on le stocke en session pour l'utiliser par la suite et on redirige vers une route interne protégée qui va déclencher l'identification FranceConnect // si le challenge est validé par hydra, on le stocke en session pour l'utiliser par la suite et on redirige vers une route interne protégée qui va déclencher l'identification FranceConnect
$request->getSession()->set('hydraChallenge', $challenge); $request->getSession()->set('hydraChallenge', $challenge);
@ -115,60 +117,64 @@ class HydraController extends AbstractController
// Récupération des data du formulaire // Récupération des data du formulaire
$form->handleRequest($request); $form->handleRequest($request);
// Affichage du formulaire // Affichage du formulaire
return $this->render("Home/loginHYDRA.html.twig", [ return $this->render('Home/loginHYDRA.html.twig', [
"useheader"=>false, 'useheader' => false,
"usemenu"=>false, 'usemenu' => false,
"usesidebar"=>false, 'usesidebar' => false,
"form"=>$form->createView(), 'form' => $form->createView(),
"mode"=>"LDAP", 'mode' => 'LDAP',
]); ]);
} }
public function checkloginldap(Request $request,ManagerRegistry $em) { public function checkloginldap(Request $request, ManagerRegistry $em)
$username=$request->get('login')["username"]; {
$password=$request->get('login')["password"]; $username = $request->get('login')['username'];
$password = $request->get('login')['password'];
// L'utilisateur se co à l'annuaire ? // L'utilisateur se co à l'annuaire ?
$userldap = $this->ldapservice->userconnect($username, $password); $userldap = $this->ldapservice->userconnect($username, $password);
if(!$userldap) if (!$userldap) {
return $this->redirect($this->generateUrl('app_hydra_loginldap',["login_challenge"=>$request->getSession()->get("hydraChallenge")])); return $this->redirect($this->generateUrl('app_hydra_loginldap', ['login_challenge' => $request->getSession()->get('hydraChallenge')]));
}
$userldap = $userldap[0]; $userldap = $userldap[0];
// Init // Init
$email = "$username@nomail.fr"; $email = "$username@nomail.fr";
$lastname = $username; $lastname = $username;
$firstname = " "; $firstname = ' ';
// Rechercher l'utilisateur // Rechercher l'utilisateur
if(isset($userldap[$this->getParameter('ldapFirstname')])) if (isset($userldap[$this->getParameter('ldapFirstname')])) {
$firstname = $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')];
$response = $this->apiservice->run("PUT",$this->getParameter('hydraLoginchallengeaccept').$request->getSession()->get('hydraChallenge'),["subject"=>$email,"acr"=>"string"]);
if(!$response||$response->code!="200")
throw new BadRequestException('login accept invalide');
$datas=[
"username"=>$username,
"email"=>$email,
"firstname"=>$firstname,
"lastname"=>$lastname
];
$request->getSession()->set("datas",$datas);
$redirect=$response->body->redirect_to;
return $this->redirect($redirect, 301);
} }
if (isset($userldap[$this->getParameter('ldapLastname')])) {
$lastname = $userldap[$this->getParameter('ldapLastname')];
}
if (isset($userldap[$this->getParameter('ldapEmail')])) {
$email = $userldap[$this->getParameter('ldapEmail')];
}
$response = $this->apiservice->run('PUT', $this->getParameter('hydraLoginchallengeaccept').$request->getSession()->get('hydraChallenge'), ['subject' => $email, 'acr' => 'string']);
if (!$response || '200' != $response->code) {
throw new BadRequestException('login accept invalide');
}
$datas = [
'username' => $username,
'email' => $email,
'firstname' => $firstname,
'lastname' => $lastname,
];
$request->getSession()->set('datas', $datas);
$redirect = $response->body->redirect_to;
return $this->redirect($redirect, 301);
}
public function consent(Request $request) public function consent(Request $request)
{ {
@ -178,20 +184,22 @@ class HydraController extends AbstractController
} }
// On vérifie que la requête d'identification provient bien de hydra // On vérifie que la requête d'identification provient bien de hydra
$response = $this->apiservice->run("GET",$this->getParameter('hydraConsentchallenge').$challenge,null); $response = $this->apiservice->run('GET', $this->getParameter('hydraConsentchallenge').$challenge, null);
if(!$response) if (!$response) {
throw new BadRequestException('challenge invalide'); throw new BadRequestException('challenge invalide');
}
$response = $this->apiservice->run("PUT",$this->getParameter('hydraConsentchallengeaccept').$challenge,[ $response = $this->apiservice->run('PUT', $this->getParameter('hydraConsentchallengeaccept').$challenge, [
'grant_scope' => ['openid', 'offline_access'], 'grant_scope' => ['openid', 'offline_access'],
'session' => ['id_token' => $request->getSession()->get('datas')] 'session' => ['id_token' => $request->getSession()->get('datas')],
]); ]);
if(!$response) if (!$response) {
throw new BadRequestException('challenge not accept'); throw new BadRequestException('challenge not accept');
}
$redirect = $response->body->redirect_to; $redirect = $response->body->redirect_to;
return $this->redirect($redirect, 301); return $this->redirect($redirect, 301);
} }
} }

View File

@ -2,12 +2,12 @@
namespace App\Controller; namespace App\Controller;
use App\Service\MinioService;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Response;
use App\Service\MinioService;
use Symfony\Component\HttpKernel\KernelInterface; use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\Filesystem\Filesystem;
class MinioController extends AbstractController class MinioController extends AbstractController
{ {
@ -29,45 +29,45 @@ class MinioController extends AbstractController
// Répertoire de Destination // Répertoire de Destination
$fs = new Filesystem(); $fs = new Filesystem();
$rootdir = $this->getParameter('kernel.project_dir').'/var/tmp'; $rootdir = $this->getParameter('kernel.project_dir').'/var/tmp';
$fs->mkdir($rootdir."/ckeditor"); $fs->mkdir($rootdir.'/ckeditor');
// Fichier cible // Fichier cible
$targetName = uniqid().".".$extention; $targetName = uniqid().'.'.$extention;
$targetFile = "ckeditor/".$targetName; $targetFile = 'ckeditor/'.$targetName;
$targetUrl = $this->generateUrl('app_minio_document',["file"=>"ckeditor/".$targetName]); $targetUrl = $this->generateUrl('app_minio_document', ['file' => 'ckeditor/'.$targetName]);
// move_uploaded_file($tmpfile,$targetFile); // move_uploaded_file($tmpfile,$targetFile);
$this->minio->upload($tmpfile, $targetFile, true); $this->minio->upload($tmpfile, $targetFile, true);
$output["uploaded"]=1; $output['uploaded'] = 1;
$output["fileName"]=$targetName; $output['fileName'] = $targetName;
$output["url"]=$targetUrl; $output['url'] = $targetUrl;
return new Response(json_encode($output)); return new Response(json_encode($output));
} }
public function logo(Request $request): Response { public function logo(Request $request): Response
{
return $this->redirectToRoute("app_minio_image",["file"=>"logo/".$request->getSession()->get("logolight")]); return $this->redirectToRoute('app_minio_image', ['file' => 'logo/'.$request->getSession()->get('logolight')]);
} }
public function image(Request $request): Response public function image(Request $request): Response
{ {
$file=$request->query->get("file"); $file = $request->query->get('file');
switch ($file) { switch ($file) {
case "avatar/admin.jpg": case 'avatar/admin.jpg':
case "avatar/noavatar.png": case 'avatar/noavatar.png':
case "avatar/system.jpg": case 'avatar/system.jpg':
case "header/header.jpg": case 'header/header.jpg':
case "logo/logo.png": case 'logo/logo.png':
$file = "medias/".$file; $file = 'medias/'.$file;
$filePath = $file; $filePath = $file;
$content = file_get_contents($file); $content = file_get_contents($file);
break; break;
default: default:
// C'est une url = on affiche l'url // C'est une url = on affiche l'url
if(stripos($file,"http")===0) { if (0 === stripos($file, 'http')) {
$filePath = $file; $filePath = $file;
$content = file_get_contents($file); $content = file_get_contents($file);
} }
@ -88,7 +88,7 @@ class MinioController extends AbstractController
public function document(Request $request) public function document(Request $request)
{ {
$file=$request->query->get("file"); $file = $request->query->get('file');
$filePath = $this->minio->download($file, $file, true); $filePath = $this->minio->download($file, $file, true);
$content = file_get_contents($filePath); $content = file_get_contents($filePath);

View File

@ -1,31 +1,30 @@
<?php <?php
namespace App\Controller; 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\Entity\Niveau01 as Entity;
use App\Form\Niveau01Type as Form; use App\Form\Niveau01Type as Form;
use Doctrine\Persistence\ManagerRegistry;
use Ramsey\Uuid\Uuid;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class Niveau01Controller extends AbstractController class Niveau01Controller extends AbstractController
{ {
private $data="niveau01"; private $data = 'niveau01';
private $entity = "App\Entity\Niveau01"; private $entity = "App\Entity\Niveau01";
private $twig="Niveau01/"; private $twig = 'Niveau01/';
private $route="app_admin_niveau01"; private $route = 'app_admin_niveau01';
public function list($access): Response public function list($access): Response
{ {
return $this->render($this->twig.'list.html.twig', [ return $this->render($this->twig.'list.html.twig', [
"useheader"=>true, 'useheader' => true,
"usemenu"=>false, 'usemenu' => false,
"usesidebar"=>true, 'usesidebar' => true,
"access"=>$access, 'access' => $access,
]); ]);
} }
@ -43,32 +42,32 @@ class Niveau01Controller extends AbstractController
$total = $em->getManager()->createQueryBuilder()->select('COUNT(entity)')->from($this->entity, 'entity')->getQuery()->getSingleScalarResult(); $total = $em->getManager()->createQueryBuilder()->select('COUNT(entity)')->from($this->entity, 'entity')->getQuery()->getSingleScalarResult();
// Nombre d'enregistrement filtré // Nombre d'enregistrement filtré
if(!$search||$search["value"]=="") if (!$search || '' == $search['value']) {
$totalf = $total; $totalf = $total;
else { } else {
$totalf = $em->getManager()->createQueryBuilder() $totalf = $em->getManager()->createQueryBuilder()
->select('COUNT(entity)') ->select('COUNT(entity)')
->from($this->entity, 'entity') ->from($this->entity, 'entity')
->where('entity.label LIKE :value') ->where('entity.label LIKE :value')
->setParameter("value", "%".$search["value"]."%") ->setParameter('value', '%'.$search['value'].'%')
->getQuery() ->getQuery()
->getSingleScalarResult(); ->getSingleScalarResult();
} }
// Construction du tableau de retour // Construction du tableau de retour
$output = array( $output = [
'draw' => $draw, 'draw' => $draw,
'recordsFiltered' => $totalf, 'recordsFiltered' => $totalf,
'recordsTotal' => $total, 'recordsTotal' => $total,
'data' => array(), 'data' => [],
); ];
// Parcours des Enregistrement // Parcours des Enregistrement
$qb = $em->getManager()->createQueryBuilder(); $qb = $em->getManager()->createQueryBuilder();
$qb->select('entity')->from($this->entity, 'entity'); $qb->select('entity')->from($this->entity, 'entity');
if($search&&$search["value"]!="") { if ($search && '' != $search['value']) {
$qb->andWhere('entity.label LIKE :value') $qb->andWhere('entity.label LIKE :value')
->setParameter("value", "%".$search["value"]."%"); ->setParameter('value', '%'.$search['value'].'%');
} }
if ($ordercolumn) { if ($ordercolumn) {
@ -83,24 +82,27 @@ class Niveau01Controller extends AbstractController
foreach ($datas as $data) { foreach ($datas as $data) {
// Action // Action
$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>"; $action .= "<a href='".$this->generateUrl($this->route.'_update', ['id' => $data->getId()])."'><i class='fa fa-file fa-fw fa-2x'></i></a>";
$tmp=array(); $tmp = [];
array_push($tmp, $action); array_push($tmp, $action);
array_push($tmp, $data->getLabel()); array_push($tmp, $data->getLabel());
if($this->getParameter("appMasteridentity")=="LDAP"||$this->getParameter("appSynchro")=="LDAP2NINE") array_push($tmp,$data->getLdapfilter()); if ('LDAP' == $this->getParameter('appMasteridentity') || 'LDAP2NINE' == $this->getParameter('appSynchro')) {
if($this->getParameter("appMasteridentity")=="SSO") array_push($tmp,$data->getAttributes()); array_push($tmp, $data->getLdapfilter());
}
if ('SSO' == $this->getParameter('appMasteridentity')) {
array_push($tmp, $data->getAttributes());
}
array_push($output["data"],$tmp); array_push($output['data'], $tmp);
} }
// Retour // Retour
return new JsonResponse($output); return new JsonResponse($output);
} }
public function submit($access, Request $request, ManagerRegistry $em): Response public function submit($access, Request $request, ManagerRegistry $em): Response
{ {
// Initialisation de l'enregistrement // Initialisation de l'enregistrement
@ -108,12 +110,12 @@ class Niveau01Controller extends AbstractController
$data->setApikey(Uuid::uuid4()); $data->setApikey(Uuid::uuid4());
// Création du formulaire // Création du formulaire
$form = $this->createForm(Form::class,$data,array( $form = $this->createForm(Form::class, $data, [
"mode"=>"submit", 'mode' => 'submit',
"appMasteridentity"=>$this->GetParameter("appMasteridentity"), 'appMasteridentity' => $this->GetParameter('appMasteridentity'),
"appSynchro"=>$this->GetParameter("appSynchro"), 'appSynchro' => $this->GetParameter('appSynchro'),
"appNiveau01label"=>$this->GetParameter("appNiveau01label"), 'appNiveau01label' => $this->GetParameter('appNiveau01label'),
)); ]);
// Récupération des data du formulaire // Récupération des data du formulaire
$form->handleRequest($request); $form->handleRequest($request);
@ -132,13 +134,13 @@ class Niveau01Controller extends AbstractController
// Affichage du formulaire // Affichage du formulaire
return $this->render($this->twig.'edit.html.twig', [ return $this->render($this->twig.'edit.html.twig', [
"useheader"=>true, 'useheader' => true,
"usemenu"=>false, 'usemenu' => false,
"usesidebar"=>true, 'usesidebar' => true,
"mode"=>"submit", 'mode' => 'submit',
"form"=>$form->createView(), 'form' => $form->createView(),
$this->data => $data, $this->data => $data,
"access"=>$access, 'access' => $access,
]); ]);
} }
@ -146,15 +148,17 @@ class Niveau01Controller extends AbstractController
{ {
// Initialisation de l'enregistrement // Initialisation de l'enregistrement
$data = $em->getRepository($this->entity)->find($id); $data = $em->getRepository($this->entity)->find($id);
if (!$data) throw $this->createNotFoundException('Unable to find entity.'); if (!$data) {
throw $this->createNotFoundException('Unable to find entity.');
}
// Création du formulaire // Création du formulaire
$form = $this->createForm(Form::class,$data,array( $form = $this->createForm(Form::class, $data, [
"mode"=>"update", 'mode' => 'update',
"appMasteridentity"=>$this->GetParameter("appMasteridentity"), 'appMasteridentity' => $this->GetParameter('appMasteridentity'),
"appSynchro"=>$this->GetParameter("appSynchro"), 'appSynchro' => $this->GetParameter('appSynchro'),
"appNiveau01label"=>$this->GetParameter("appNiveau01label"), 'appNiveau01label' => $this->GetParameter('appNiveau01label'),
)); ]);
// Récupération des data du formulaire // Récupération des data du formulaire
$form->handleRequest($request); $form->handleRequest($request);
@ -176,7 +180,7 @@ class Niveau01Controller extends AbstractController
$this->data => $data, $this->data => $data,
'mode' => 'update', 'mode' => 'update',
'form' => $form->createView(), 'form' => $form->createView(),
"access" => $access 'access' => $access,
]); ]);
} }
@ -184,16 +188,18 @@ class Niveau01Controller extends AbstractController
{ {
// Récupération de l'enregistrement courant // Récupération de l'enregistrement courant
$data = $em->getRepository($this->entity)->find($id); $data = $em->getRepository($this->entity)->find($id);
if (!$data) throw $this->createNotFoundException('Unable to find entity.'); if (!$data) {
throw $this->createNotFoundException('Unable to find entity.');
}
// Tentative de suppression // Tentative de suppression
try { try {
$em->getManager()->remove($data); $em->getManager()->remove($data);
$em->getManager()->flush(); $em->getManager()->flush();
} } catch (\Exception $e) {
catch (\Exception $e) { $request->getSession()->getFlashBag()->add('error', $e->getMessage());
$request->getSession()->getFlashBag()->add("error", $e->getMessage());
return $this->redirectToRoute($this->route."_update",["id"=>$id]); return $this->redirectToRoute($this->route.'_update', ['id' => $id]);
} }
return $this->redirectToRoute($this->route); return $this->redirectToRoute($this->route);

View File

@ -1,31 +1,30 @@
<?php <?php
namespace App\Controller; 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\Entity\Niveau02 as Entity;
use App\Form\Niveau02Type as Form; use App\Form\Niveau02Type as Form;
use Doctrine\Persistence\ManagerRegistry;
use Ramsey\Uuid\Uuid;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class Niveau02Controller extends AbstractController class Niveau02Controller extends AbstractController
{ {
private $data="niveau02"; private $data = 'niveau02';
private $entity = "App\Entity\Niveau02"; private $entity = "App\Entity\Niveau02";
private $twig="Niveau02/"; private $twig = 'Niveau02/';
private $route="app_admin_niveau02"; private $route = 'app_admin_niveau02';
public function list($access): Response public function list($access): Response
{ {
return $this->render($this->twig.'list.html.twig', [ return $this->render($this->twig.'list.html.twig', [
"useheader"=>true, 'useheader' => true,
"usemenu"=>false, 'usemenu' => false,
"usesidebar"=>true, 'usesidebar' => true,
"access"=>$access, 'access' => $access,
]); ]);
} }
@ -43,42 +42,40 @@ class Niveau02Controller extends AbstractController
// Nombre total d'enregistrement // Nombre total d'enregistrement
switch ($access) { switch ($access) {
case "admin": case 'admin':
$total = $em->getManager()->createQueryBuilder()->select('COUNT(entity)')->from($this->entity, 'entity')->getQuery()->getSingleScalarResult(); $total = $em->getManager()->createQueryBuilder()->select('COUNT(entity)')->from($this->entity, 'entity')->getQuery()->getSingleScalarResult();
break; break;
case "modo": case 'modo':
$total = $em->getManager()->createQueryBuilder() $total = $em->getManager()->createQueryBuilder()
->select('COUNT(entity)') ->select('COUNT(entity)')
->from($this->entity, 'entity') ->from($this->entity, 'entity')
->from("App\Entity\UserModo", 'usermodo') ->from("App\Entity\UserModo", 'usermodo')
->where("usermodo.niveau01 = entity.niveau01") ->where('usermodo.niveau01 = entity.niveau01')
->andWhere("usermodo.user = :user") ->andWhere('usermodo.user = :user')
->setParameter("user", $this->getUser()) ->setParameter('user', $this->getUser())
->getQuery()->getSingleScalarResult(); ->getQuery()->getSingleScalarResult();
break; break;
} }
// Nombre d'enregistrement filtré // Nombre d'enregistrement filtré
if(!$search||$search["value"]=="") if (!$search || '' == $search['value']) {
$totalf = $total; $totalf = $total;
else { } else {
switch ($access) { switch ($access) {
case "admin": case 'admin':
$totalf = $em->getManager()->createQueryBuilder() $totalf = $em->getManager()->createQueryBuilder()
->select('COUNT(entity)') ->select('COUNT(entity)')
->from($this->entity, 'entity') ->from($this->entity, 'entity')
->from("App\Entity\Niveau01", 'niveau01') ->from("App\Entity\Niveau01", 'niveau01')
->where('entity.niveau01=niveau01.id') ->where('entity.niveau01=niveau01.id')
->andwhere('entity.label LIKE :value OR niveau01.label LIKE :value') ->andwhere('entity.label LIKE :value OR niveau01.label LIKE :value')
->setParameter("value", "%".$search["value"]."%") ->setParameter('value', '%'.$search['value'].'%')
->getQuery() ->getQuery()
->getSingleScalarResult(); ->getSingleScalarResult();
break; break;
case "modo": case 'modo':
$totalf = $em->getManager()->createQueryBuilder() $totalf = $em->getManager()->createQueryBuilder()
->select('COUNT(entity)') ->select('COUNT(entity)')
->from($this->entity, 'entity') ->from($this->entity, 'entity')
@ -86,10 +83,10 @@ class Niveau02Controller extends AbstractController
->from("App\Entity\UserModo", 'usermodo') ->from("App\Entity\UserModo", 'usermodo')
->where('entity.niveau01=niveau01.id') ->where('entity.niveau01=niveau01.id')
->andwhere('entity.label LIKE :value OR niveau01.label LIKE :value') ->andwhere('entity.label LIKE :value OR niveau01.label LIKE :value')
->andWhere("usermodo.niveau01 = entity.niveau01") ->andWhere('usermodo.niveau01 = entity.niveau01')
->andWhere("usermodo.user = :user") ->andWhere('usermodo.user = :user')
->setParameter("value", "%".$search["value"]."%") ->setParameter('value', '%'.$search['value'].'%')
->setParameter("user", $this->getUser()) ->setParameter('user', $this->getUser())
->getQuery() ->getQuery()
->getSingleScalarResult(); ->getSingleScalarResult();
break; break;
@ -97,38 +94,38 @@ class Niveau02Controller extends AbstractController
} }
// Construction du tableau de retour // Construction du tableau de retour
$output = array( $output = [
'draw' => $draw, 'draw' => $draw,
'recordsFiltered' => $totalf, 'recordsFiltered' => $totalf,
'recordsTotal' => $total, 'recordsTotal' => $total,
'data' => array(), 'data' => [],
); ];
// Parcours des Enregistrement // Parcours des Enregistrement
$qb = $em->getManager()->createQueryBuilder(); $qb = $em->getManager()->createQueryBuilder();
switch ($access) { switch ($access) {
case "admin": case 'admin':
$qb->select('entity') $qb->select('entity')
->from($this->entity, 'entity') ->from($this->entity, 'entity')
->from("App:Niveau01",'niveau01') ->from('App:Niveau01', 'niveau01')
->where('entity.niveau01=niveau01.id'); ->where('entity.niveau01=niveau01.id');
break; break;
case "modo": case 'modo':
$qb->select('entity') $qb->select('entity')
->from($this->entity, 'entity') ->from($this->entity, 'entity')
->from("App:Niveau01",'niveau01') ->from('App:Niveau01', 'niveau01')
->from("App\Entity\UserModo", 'usermodo') ->from("App\Entity\UserModo", 'usermodo')
->where('entity.niveau01=niveau01.id') ->where('entity.niveau01=niveau01.id')
->andWhere("usermodo.niveau01 = entity.niveau01") ->andWhere('usermodo.niveau01 = entity.niveau01')
->andWhere("usermodo.user = :user") ->andWhere('usermodo.user = :user')
->setParameter("user", $this->getUser()); ->setParameter('user', $this->getUser());
break; break;
} }
if($search&&$search["value"]!="") { if ($search && '' != $search['value']) {
$qb->andwhere('entity.label LIKE :value OR niveau01.label LIKE :value') $qb->andwhere('entity.label LIKE :value OR niveau01.label LIKE :value')
->setParameter("value", "%".$search["value"]."%"); ->setParameter('value', '%'.$search['value'].'%');
} }
if ($ordercolumn) { if ($ordercolumn) {
@ -147,22 +144,22 @@ class Niveau02Controller extends AbstractController
foreach ($datas as $data) { foreach ($datas as $data) {
// Action // Action
$action = ""; $action = '';
switch ($access) { switch ($access) {
case "admin": 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>"; $action .= "<a href='".$this->generateUrl($this->route.'_update', ['id' => $data->getId()])."'><i class='fa fa-file fa-fw fa-2x'></i></a>";
break; break;
case "modo": 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>"; $action .= "<a href='".$this->generateUrl(str_replace('_admin_', '_modo_', $this->route).'_update', ['id' => $data->getId()])."'><i class='fa fa-file fa-fw fa-2x'></i></a>";
break; break;
} }
$tmp=array(); $tmp = [];
array_push($tmp, $action); array_push($tmp, $action);
array_push($tmp, $data->getNiveau01()->getLabel()); array_push($tmp, $data->getNiveau01()->getLabel());
array_push($tmp, $data->getLabel()); array_push($tmp, $data->getLabel());
array_push($output["data"],$tmp); array_push($output['data'], $tmp);
} }
// Retour // Retour
@ -171,7 +168,7 @@ class Niveau02Controller extends AbstractController
public function selectlist(Request $request, ManagerRegistry $em): Response public function selectlist(Request $request, ManagerRegistry $em): Response
{ {
$output=array(); $output = [];
$page_limit = $request->query->get('page_limit'); $page_limit = $request->query->get('page_limit');
$q = $request->query->get('q'); $q = $request->query->get('q');
$niveau01id = $request->get('niveau01'); $niveau01id = $request->get('niveau01');
@ -181,18 +178,19 @@ class Niveau02Controller extends AbstractController
->from($this->entity, 'entity') ->from($this->entity, 'entity')
->where('entity.label LIKE :value') ->where('entity.label LIKE :value')
->andwhere('entity.niveau01=:niveau01') ->andwhere('entity.niveau01=:niveau01')
->setParameter("value", "%".$q."%") ->setParameter('value', '%'.$q.'%')
->setParameter("niveau01", $niveau01id) ->setParameter('niveau01', $niveau01id)
->orderBy('entity.label'); ->orderBy('entity.label');
$datas = $qb->setFirstResult(0)->setMaxResults($page_limit)->getQuery()->getResult(); $datas = $qb->setFirstResult(0)->setMaxResults($page_limit)->getQuery()->getResult();
foreach ($datas as $data) { foreach ($datas as $data) {
array_push($output,array("id"=>$data->getId(),"text"=>$data->getLabel())); array_push($output, ['id' => $data->getId(), 'text' => $data->getLabel()]);
} }
$ret_string["results"]=$output; $ret_string['results'] = $output;
$response = new Response(json_encode($ret_string)); $response = new Response(json_encode($ret_string));
$response->headers->set('Content-Type', 'application/json'); $response->headers->set('Content-Type', 'application/json');
return $response; return $response;
} }
@ -206,14 +204,14 @@ class Niveau02Controller extends AbstractController
$this->cansubmit($access, $em); $this->cansubmit($access, $em);
// Création du formulaire // Création du formulaire
$form = $this->createForm(Form::class,$data,array( $form = $this->createForm(Form::class, $data, [
"mode"=>"submit", 'mode' => 'submit',
"access"=>$access, 'access' => $access,
"userid"=>$this->getUser()->getId(), 'userid' => $this->getUser()->getId(),
"appMasteridentity"=>$this->GetParameter("appMasteridentity"), 'appMasteridentity' => $this->GetParameter('appMasteridentity'),
"appNiveau01label"=>$this->GetParameter("appNiveau01label"), 'appNiveau01label' => $this->GetParameter('appNiveau01label'),
"appNiveau02label"=>$this->GetParameter("appNiveau02label"), 'appNiveau02label' => $this->GetParameter('appNiveau02label'),
)); ]);
// Récupération des data du formulaire // Récupération des data du formulaire
$form->handleRequest($request); $form->handleRequest($request);
@ -227,17 +225,17 @@ class Niveau02Controller extends AbstractController
$em->getManager()->flush(); $em->getManager()->flush();
// Retour à la liste // Retour à la liste
return $this->redirectToRoute(str_replace("_admin_","_".$access."_",$this->route)); return $this->redirectToRoute(str_replace('_admin_', '_'.$access.'_', $this->route));
} }
// Affichage du formulaire // Affichage du formulaire
return $this->render($this->twig.'edit.html.twig', [ return $this->render($this->twig.'edit.html.twig', [
"useheader"=>true, 'useheader' => true,
"usemenu"=>false, 'usemenu' => false,
"usesidebar"=>true, 'usesidebar' => true,
"mode"=>"submit", 'mode' => 'submit',
"access"=>$access, 'access' => $access,
"form"=>$form->createView(), 'form' => $form->createView(),
$this->data => $data, $this->data => $data,
]); ]);
} }
@ -246,18 +244,20 @@ class Niveau02Controller extends AbstractController
{ {
// Initialisation de l'enregistrement // Initialisation de l'enregistrement
$data = $em->getRepository($this->entity)->find($id); $data = $em->getRepository($this->entity)->find($id);
if (!$data) throw $this->createNotFoundException('Unable to find entity.'); if (!$data) {
throw $this->createNotFoundException('Unable to find entity.');
}
// Controler les permissions // Controler les permissions
$this->canupdate($access, $data, $em); $this->canupdate($access, $data, $em);
// Création du formulaire // Création du formulaire
$form = $this->createForm(Form::class,$data,array( $form = $this->createForm(Form::class, $data, [
"mode"=>"update", 'mode' => 'update',
"appMasteridentity"=>$this->GetParameter("appMasteridentity"), 'appMasteridentity' => $this->GetParameter('appMasteridentity'),
"appNiveau01label"=>$this->GetParameter("appNiveau01label"), 'appNiveau01label' => $this->GetParameter('appNiveau01label'),
"appNiveau02label"=>$this->GetParameter("appNiveau02label"), 'appNiveau02label' => $this->GetParameter('appNiveau02label'),
)); ]);
// Récupération des data du formulaire // Récupération des data du formulaire
$form->handleRequest($request); $form->handleRequest($request);
@ -268,7 +268,7 @@ class Niveau02Controller extends AbstractController
$em->getManager()->flush(); $em->getManager()->flush();
// Retour à la liste // Retour à la liste
return $this->redirectToRoute(str_replace("_admin_","_".$access."_",$this->route)); return $this->redirectToRoute(str_replace('_admin_', '_'.$access.'_', $this->route));
} }
// Affichage du formulaire // Affichage du formulaire
@ -279,7 +279,7 @@ class Niveau02Controller extends AbstractController
$this->data => $data, $this->data => $data,
'mode' => 'update', 'mode' => 'update',
'access' => $access, 'access' => $access,
'form' => $form->createView() 'form' => $form->createView(),
]); ]);
} }
@ -287,7 +287,9 @@ class Niveau02Controller extends AbstractController
{ {
// Récupération de l'enregistrement courant // Récupération de l'enregistrement courant
$data = $em->getRepository($this->entity)->find($id); $data = $em->getRepository($this->entity)->find($id);
if (!$data) throw $this->createNotFoundException('Unable to find entity.'); if (!$data) {
throw $this->createNotFoundException('Unable to find entity.');
}
// Controler les permissions // Controler les permissions
$this->canupdate($access, $data, $em); $this->canupdate($access, $data, $em);
@ -296,30 +298,37 @@ class Niveau02Controller extends AbstractController
try { try {
$em->getManager()->remove($data); $em->getManager()->remove($data);
$em->getManager()->flush(); $em->getManager()->flush();
} } catch (\Exception $e) {
catch (\Exception $e) { $request->getSession()->getFlashBag()->add('error', $e->getMessage());
$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).'_update', ['id' => $id]);
} }
return $this->redirectToRoute(str_replace("_admin_","_".$access."_",$this->route)); return $this->redirectToRoute(str_replace('_admin_', '_'.$access.'_', $this->route));
} }
private function cansubmit($access,$em) { private function cansubmit($access, $em)
{
switch ($access) { switch ($access) {
case "admin" : return true; break; case 'admin': return true;
case "modo" : return true; break; break;
case 'modo': return true;
break;
} }
throw $this->createAccessDeniedException('Permission denied'); throw $this->createAccessDeniedException('Permission denied');
} }
private function canupdate($access, $entity, $em)
private function canupdate($access,$entity,$em) { {
switch ($access) { switch ($access) {
case "admin" : return true; break; case 'admin': return true;
case "modo" : break;
$usermodo=$em->getRepository("App\Entity\UserModo")->findOneBy(["user"=>$this->getUser(),"niveau01"=>$entity->getNiveau01()]); case 'modo':
if(!$usermodo) throw $this->createAccessDeniedException('Permission denied'); $usermodo = $em->getRepository("App\Entity\UserModo")->findOneBy(['user' => $this->getUser(), 'niveau01' => $entity->getNiveau01()]);
if (!$usermodo) {
throw $this->createAccessDeniedException('Permission denied');
}
return true; return true;
break; break;
} }

View File

@ -1,4 +1,5 @@
<?php <?php
namespace App\Controller; namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
@ -9,24 +10,24 @@ use Symfony\Component\Mercure\Update;
class PublishController extends AbstractController class PublishController extends AbstractController
{ {
public function sample($id){ public function sample($id)
{
return $this->render('Home/publishsample.html.twig', [ return $this->render('Home/publishsample.html.twig', [
'id'=>$id 'id' => $id,
]); ]);
} }
public function publish($channel, $id, Request $request, HubInterface $hub): Response public function publish($channel, $id, Request $request, HubInterface $hub): Response
{ {
$ret=$request->get("msg"); $ret = $request->get('msg');
$ret["from"]=[]; $ret['from'] = [];
$ret["from"]["id"]=$this->getUser()->getId(); $ret['from']['id'] = $this->getUser()->getId();
$ret["from"]["username"]=$this->getUser()->getUsername(); $ret['from']['username'] = $this->getUser()->getUsername();
$ret["from"]["displayname"]=$this->getUser()->getDisplayname(); $ret['from']['displayname'] = $this->getUser()->getDisplayname();
$ret["from"]["avatar"]=$this->generateUrl('app_minio_image',["file"=>"avatar/".$this->getUser()->getAvatar()]); $ret['from']['avatar'] = $this->generateUrl('app_minio_image', ['file' => 'avatar/'.$this->getUser()->getAvatar()]);
$update = new Update( $update = new Update(
$channel."-".$id, $channel.'-'.$id,
json_encode( json_encode(
['ret' => $ret]) ['ret' => $ret])
); );

View File

@ -2,32 +2,31 @@
namespace App\Controller; 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\Registration; use App\Entity\Registration;
use App\Entity\User;
use App\Form\RegistrationType as Form; use App\Form\RegistrationType as Form;
use App\Form\ResetpwdType; use App\Form\ResetpwdType;
use App\Service\MailService;
use Doctrine\Persistence\ManagerRegistry;
use Ramsey\Uuid\Uuid;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\FormError;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
class RegistrationController extends AbstractController class RegistrationController extends AbstractController
{ {
private $data="registration"; private $data = 'registration';
private $entity = "App\Entity\Registration"; private $entity = "App\Entity\Registration";
private $twig="Registration/"; private $twig = 'Registration/';
private $route="app_admin_registration"; private $route = 'app_admin_registration';
private $mail; private $mail;
public function __construct(MailService $mail) {
public function __construct(MailService $mail)
{
$this->mail = $mail; $this->mail = $mail;
} }
@ -35,8 +34,9 @@ class RegistrationController extends AbstractController
{ {
$appmoderegistration = $this->getParameter('appModeregistration'); $appmoderegistration = $this->getParameter('appModeregistration');
$appMasteridentity = $this->getParameter('appMasteridentity'); $appMasteridentity = $this->getParameter('appMasteridentity');
if($appmoderegistration=="none"||$appMasteridentity!="SQL") if ('none' == $appmoderegistration || 'SQL' != $appMasteridentity) {
throw $this->createAccessDeniedException('Permission denied'); throw $this->createAccessDeniedException('Permission denied');
}
return $this->render($this->twig.'list.html.twig', [ return $this->render($this->twig.'list.html.twig', [
'useheader' => true, 'useheader' => true,
@ -48,7 +48,6 @@ class RegistrationController extends AbstractController
public function tablelist($access, Request $request, ManagerRegistry $em): Response public function tablelist($access, Request $request, ManagerRegistry $em): Response
{ {
$query = $request->query->all(); $query = $request->query->all();
$start = $query['start']; $start = $query['start'];
$length = $query['length']; $length = $query['length'];
@ -59,73 +58,72 @@ class RegistrationController extends AbstractController
$usermodo = null; $usermodo = null;
// Nombre total d'enregistrement // Nombre total d'enregistrement
if($access=="admin") if ('admin' == $access) {
$total = $em->getManager()->createQueryBuilder()->select('COUNT(entity)')->from($this->entity, 'entity')->getQuery()->getSingleScalarResult(); $total = $em->getManager()->createQueryBuilder()->select('COUNT(entity)')->from($this->entity, 'entity')->getQuery()->getSingleScalarResult();
else { } else {
$usermodo = $this->getUser(); $usermodo = $this->getUser();
$total = $em->getManager()->createQueryBuilder() $total = $em->getManager()->createQueryBuilder()
->select('COUNT(entity)') ->select('COUNT(entity)')
->from($this->entity, 'entity') ->from($this->entity, 'entity')
->from("App:UserModo",'usermodo') ->from('App:UserModo', 'usermodo')
->where("usermodo.niveau01 = entity.niveau01") ->where('usermodo.niveau01 = entity.niveau01')
->andWhere("usermodo.user = :user") ->andWhere('usermodo.user = :user')
->setParameter("user", $usermodo) ->setParameter('user', $usermodo)
->getQuery()->getSingleScalarResult(); ->getQuery()->getSingleScalarResult();
} }
// Nombre d'enregistrement filtré // Nombre d'enregistrement filtré
if($search["value"]=="") if ('' == $search['value']) {
$totalf = $total; $totalf = $total;
else { } else {
if($access=="admin") if ('admin' == $access) {
$totalf = $em->getManager()->createQueryBuilder() $totalf = $em->getManager()->createQueryBuilder()
->select('COUNT(entity)') ->select('COUNT(entity)')
->from($this->entity, 'entity') ->from($this->entity, 'entity')
->where('entity.username LIKE :value') ->where('entity.username LIKE :value')
->orWhere('entity.email LIKE :value') ->orWhere('entity.email LIKE :value')
->setParameter("value", "%".$search["value"]."%") ->setParameter('value', '%'.$search['value'].'%')
->getQuery() ->getQuery()
->getSingleScalarResult(); ->getSingleScalarResult();
else } else {
$totalf = $em->getManager()->createQueryBuilder() $totalf = $em->getManager()->createQueryBuilder()
->select('COUNT(entity)') ->select('COUNT(entity)')
->from($this->entity, 'entity') ->from($this->entity, 'entity')
->from("App:UserModo",'usermodo') ->from('App:UserModo', 'usermodo')
->where('entity.username LIKE :value OR entity.email LIKE :value') ->where('entity.username LIKE :value OR entity.email LIKE :value')
->andWhere("usermodo.niveau01 = entity.niveau01") ->andWhere('usermodo.niveau01 = entity.niveau01')
->andWhere("usermodo.user = :user") ->andWhere('usermodo.user = :user')
->setParameter("value", "%".$search["value"]."%") ->setParameter('value', '%'.$search['value'].'%')
->setParameter("user", $usermodo) ->setParameter('user', $usermodo)
->getQuery() ->getQuery()
->getSingleScalarResult(); ->getSingleScalarResult();
} }
}
// Construction du tableau de retour // Construction du tableau de retour
$output = array( $output = [
'draw' => $draw, 'draw' => $draw,
'recordsFiltered' => $totalf, 'recordsFiltered' => $totalf,
'recordsTotal' => $total, 'recordsTotal' => $total,
'data' => array(), 'data' => [],
); ];
// Parcours des Enregistrement // Parcours des Enregistrement
$qb = $em->getManager()->createQueryBuilder(); $qb = $em->getManager()->createQueryBuilder();
if ($this->isGranted('ROLE_ADMIN')) { if ($this->isGranted('ROLE_ADMIN')) {
$qb->select('entity')->from($this->entity, 'entity')->from('App:Niveau01', 'niveau01'); $qb->select('entity')->from($this->entity, 'entity')->from('App:Niveau01', 'niveau01');
$qb->where('entity.niveau01=niveau01.id'); $qb->where('entity.niveau01=niveau01.id');
} } else {
else{ $qb->select('entity')->from($this->entity, 'entity')->from('App:Niveau01', 'niveau01')->from('App:UserModo', 'usermodo');
$qb->select('entity')->from($this->entity,'entity')->from('App:Niveau01','niveau01')->from("App:UserModo",'usermodo');
$qb->where('entity.niveau01=niveau01.id') $qb->where('entity.niveau01=niveau01.id')
->andWhere("usermodo.niveau01 = entity.niveau01") ->andWhere('usermodo.niveau01 = entity.niveau01')
->andWhere("usermodo.user = :user") ->andWhere('usermodo.user = :user')
->setParameter("user", $usermodo); ->setParameter('user', $usermodo);
} }
if ('' != $search['value']) {
if($search["value"]!="") {
$qb->andWhere('entity.username LIKE :value OR entity.email LIKE :value OR niveau01.label LIKE :value') $qb->andWhere('entity.username LIKE :value OR entity.email LIKE :value OR niveau01.label LIKE :value')
->setParameter("value", "%".$search["value"]."%"); ->setParameter('value', '%'.$search['value'].'%');
} }
switch ($ordercolumn) { switch ($ordercolumn) {
case 1: case 1:
@ -152,74 +150,75 @@ class RegistrationController extends AbstractController
$datas = $qb->setFirstResult($start)->setMaxResults($length)->getQuery()->getResult(); $datas = $qb->setFirstResult($start)->setMaxResults($length)->getQuery()->getResult();
foreach ($datas as $data) { foreach ($datas as $data) {
$action =""; $action = '';
// Si inscription non périmée // Si inscription non périmée
if ($data->getStatut() <= 2) { 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>"; $action .= "<a href='".$this->generateUrl('app_'.$access.'_registration_update', ['id' => $data->getId()])."'><i class='fa fa-envelope fa-2x fa-fw'></i></a>";
} }
$statut=""; $statut = '';
switch ($data->getStatut()) { switch ($data->getStatut()) {
case 1: $statut='En attente validation Administration'; break; case 1: $statut = 'En attente validation Administration';
case 2: $statut='En attente validation Utilisateur'; break; break;
case 3: $statut='Inscription expirée'; break; case 2: $statut = 'En attente validation Utilisateur';
break;
case 3: $statut = 'Inscription expirée';
break;
} }
array_push($output["data"],array( array_push($output['data'], [
$action, $action,
$data->getUsername(), $data->getUsername(),
$data->getEmail(), $data->getEmail(),
$data->getNiveau01()->getLabel(), $data->getNiveau01()->getLabel(),
$statut, $statut,
(is_null($data->getKeyexpire())?"":$data->getKeyexpire()->format('d/m/Y H:i:s')) is_null($data->getKeyexpire()) ? '' : $data->getKeyexpire()->format('d/m/Y H:i:s'),
)); ]);
} }
// Retour // Retour
return new JsonResponse($output); return new JsonResponse($output);
} }
public function submit(Request $request, ManagerRegistry $em): Response public function submit(Request $request, ManagerRegistry $em): Response
{ {
$appmoderegistration = $this->getParameter('appModeregistration'); $appmoderegistration = $this->getParameter('appModeregistration');
$appMasteridentity = $this->getParameter('appMasteridentity'); $appMasteridentity = $this->getParameter('appMasteridentity');
if($appmoderegistration=="none"||$appMasteridentity!="SQL") if ('none' == $appmoderegistration || 'SQL' != $appMasteridentity) {
throw $this->createAccessDeniedException('Permission denied'); throw $this->createAccessDeniedException('Permission denied');
}
$data = new Registration(); $data = new Registration();
$data->setIsvisible(true); $data->setIsvisible(true);
// Création du formulaire // Création du formulaire
$form = $this->createForm(Form::class,$data,array( $form = $this->createForm(Form::class, $data, [
"mode"=>"submit", 'mode' => 'submit',
"access"=>"user", 'access' => 'user',
"userid"=>null, 'userid' => null,
"appMasteridentity"=>$this->GetParameter("appMasteridentity"), 'appMasteridentity' => $this->GetParameter('appMasteridentity'),
"appNiveau01label"=>$this->GetParameter("appNiveau01label"), 'appNiveau01label' => $this->GetParameter('appNiveau01label'),
"appNiveau02label"=>$this->GetParameter("appNiveau02label"), 'appNiveau02label' => $this->GetParameter('appNiveau02label'),
)); ]);
// Récupération des data du formulaire // Récupération des data du formulaire
$form->handleRequest($request); $form->handleRequest($request);
// si mode de registration BYUSER // si mode de registration BYUSER
if($appmoderegistration=="BYUSER") { if ('BYUSER' == $appmoderegistration) {
$idstatut = 2; $idstatut = 2;
} } else {
else {
// On recherche le domaine du mail dans la liste blanche // On recherche le domaine du mail dans la liste blanche
$email=explode("@",$data->getEmail()); $email = explode('@', $data->getEmail());
$domaine = end($email); $domaine = end($email);
$whitelist = $em->getRepository("App\Entity\Whitelist")->findBy(["label"=>$domaine]); $whitelist = $em->getRepository("App\Entity\Whitelist")->findBy(['label' => $domaine]);
$idstatut = (!$whitelist ? 1 : 2); $idstatut = (!$whitelist ? 1 : 2);
} }
$data->setStatut($idstatut); $data->setStatut($idstatut);
// Sur erreur // Sur erreur
$this->getErrorForm(null,$form,$request,$data,"submit",$idstatut,$em); $this->getErrorForm(null, $form, $request, $data, 'submit', $idstatut, $em);
// Sur validation // Sur validation
if ($form->get('submit')->isClicked() && $form->isValid()) { if ($form->get('submit')->isClicked() && $form->isValid()) {
@ -230,10 +229,10 @@ class RegistrationController extends AbstractController
$appModeregistrationterme = $this->getParameter('appModeregistrationterme'); $appModeregistrationterme = $this->getParameter('appModeregistrationterme');
// si non : validation par administrateur // si non : validation par administrateur
if($idstatut==1) { if (1 == $idstatut) {
// Email à destination de l'inscript pour le prévenir qu'un administrateur doit valider // Email à destination de l'inscript pour le prévenir qu'un administrateur doit valider
$subject=$appname." : Inscription en cours de validation"; $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"; $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; $info = $body;
$to = $data->getEmail(); $to = $data->getEmail();
$from = $noreply; $from = $noreply;
@ -242,59 +241,58 @@ class RegistrationController extends AbstractController
// Email à l'ensemble administrateurs pour les prévenir qu'il y a une personne à valider // Email à l'ensemble administrateurs pour les prévenir qu'il y a une personne à valider
$url = $this->generateUrl('app_admin_registration', [], UrlGeneratorInterface::ABSOLUTE_URL); $url = $this->generateUrl('app_admin_registration', [], UrlGeneratorInterface::ABSOLUTE_URL);
$to=array(); $to = [];
$from = $noreply; $from = $noreply;
$fromName = $appname; $fromName = $appname;
$subject=$appname." : Inscription à valider"; $subject = $appname.' : Inscription à valider';
$motivation = "Login = ".$data->getUsername()."<br>"; $motivation = 'Login = '.$data->getUsername().'<br>';
$motivation.= "Nom = ".$data->getLastname()."<br>"; $motivation .= 'Nom = '.$data->getLastname().'<br>';
$motivation.= "Prénom = ".$data->getFirstname()."<br>"; $motivation .= 'Prénom = '.$data->getFirstname().'<br>';
$motivation.= "Mail = ".$data->getEmail()."<br>"; $motivation .= 'Mail = '.$data->getEmail().'<br>';
$motivation.= $this->getParameter("appNiveau01label")." = ".$data->getNiveau01()->getLabel(); $motivation .= $this->getParameter('appNiveau01label').' = '.$data->getNiveau01()->getLabel();
$motivation .= $data->getMotivation(); $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; $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() $emailadmins = $em->getManager()->createQueryBuilder()
->select('table.email') ->select('table.email')
->from("App:User",'table') ->from('App:User', 'table')
->where('table.roles LIKE :value') ->where('table.roles LIKE :value')
->setParameter("value", "%ROLE_ADMIN%") ->setParameter('value', '%ROLE_ADMIN%')
->getQuery() ->getQuery()
->getResult(\Doctrine\ORM\Query::HYDRATE_SCALAR); ->getResult(\Doctrine\ORM\Query::HYDRATE_SCALAR);
foreach ($emailadmins as $emailadmin) { foreach ($emailadmins as $emailadmin) {
array_push($to,$emailadmin["email"]); array_push($to, $emailadmin['email']);
} }
$this->mail->sendEmail($subject, $body, $to, $from, $fromName); $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 // Email à l'ensemble des modérateurs du service pour les prévenir qu'il y a une personne à valider
$niveau01id = $data->getNiveau01()->getId(); $niveau01id = $data->getNiveau01()->getId();
$url = $this->generateUrl('app_modo_registration', [], UrlGeneratorInterface::ABSOLUTE_URL); $url = $this->generateUrl('app_modo_registration', [], UrlGeneratorInterface::ABSOLUTE_URL);
$to=array(); $to = [];
$from = $noreply; $from = $noreply;
$fromName = $appname; $fromName = $appname;
$subject=$appname." : Inscription à valider"; $subject = $appname.' : Inscription à valider';
$motivation = "Login = ".$data->getUsername()."<br>"; $motivation = 'Login = '.$data->getUsername().'<br>';
$motivation.= "Nom = ".$data->getLastname()."<br>"; $motivation .= 'Nom = '.$data->getLastname().'<br>';
$motivation.= "Prénom = ".$data->getFirstname()."<br>"; $motivation .= 'Prénom = '.$data->getFirstname().'<br>';
$motivation.= "Mail = ".$data->getEmail()."<br>"; $motivation .= 'Mail = '.$data->getEmail().'<br>';
$motivation.= $this->getParameter("appNiveau01label")." = ".$data->getNiveau01()->getLabel(); $motivation .= $this->getParameter('appNiveau01label').' = '.$data->getNiveau01()->getLabel();
$motivation .= $data->getMotivation(); $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; $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() $emailmodos = $em->getManager()->createQueryBuilder()
->select('user.email') ->select('user.email')
->from("App:UserModo",'usermodo') ->from('App:UserModo', 'usermodo')
->from("App:User",'user') ->from('App:User', 'user')
->where("usermodo.niveau01 = :niveau01id") ->where('usermodo.niveau01 = :niveau01id')
->andWhere("user.id = usermodo.user") ->andWhere('user.id = usermodo.user')
->andWhere('user.roles LIKE :value') ->andWhere('user.roles LIKE :value')
->setParameter("niveau01id", $niveau01id) ->setParameter('niveau01id', $niveau01id)
->setParameter("value", "%ROLE_MODO%") ->setParameter('value', '%ROLE_MODO%')
->getQuery() ->getQuery()
->getResult(\Doctrine\ORM\Query::HYDRATE_SCALAR); ->getResult(\Doctrine\ORM\Query::HYDRATE_SCALAR);
foreach ($emailmodos as $emailmodo) { foreach ($emailmodos as $emailmodo) {
array_push($to,$emailmodo["email"]); array_push($to, $emailmodo['email']);
} }
$this->mail->sendEmail($subject, $body, $to, $from, $fromName); $this->mail->sendEmail($subject, $body, $to, $from, $fromName);
} }
// si oui : Domaine de confiance : email de validation d'inscription directement à l'utilisateur // si oui : Domaine de confiance : email de validation d'inscription directement à l'utilisateur
@ -308,10 +306,10 @@ class RegistrationController extends AbstractController
$data->setKeyexpire($keyexpire); $data->setKeyexpire($keyexpire);
// Email à l'utilisateur // Email à l'utilisateur
$url = $this->generateUrl('app_registration_validation', array("key"=>$data->getKeyvalue()), UrlGeneratorInterface::ABSOLUTE_URL); $url = $this->generateUrl('app_registration_validation', ['key' => $data->getKeyvalue()], UrlGeneratorInterface::ABSOLUTE_URL);
$subject=$appname." : confirmation de validation"; $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>"; $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"; $info = 'Vous allez recevoir un mail de confirmation pour finaliser votre inscription';
$to = $data->getEmail(); $to = $data->getEmail();
$from = $noreply; $from = $noreply;
$fromName = $appname; $fromName = $appname;
@ -324,12 +322,11 @@ class RegistrationController extends AbstractController
// A voir retour sur un écran d'info indiquant si validation par admion ou s'il doit matter ses email // 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('registrationinfo', $info);
$request->getSession()->set('registrationmode', "info"); $request->getSession()->set('registrationmode', 'info');
$request->getSession()->set('registrationredirectto', null); $request->getSession()->set('registrationredirectto', null);
return $this->redirectToRoute('app_registration_info'); return $this->redirectToRoute('app_registration_info');
} } else {
else {
return $this->render($this->twig.'edit.html.twig', [ return $this->render($this->twig.'edit.html.twig', [
'useheader' => true, 'useheader' => true,
'usemenu' => false, 'usemenu' => false,
@ -337,18 +334,17 @@ class RegistrationController extends AbstractController
'maxsize' => 1200, 'maxsize' => 1200,
$this->data => $data, $this->data => $data,
'mode' => 'submit', 'mode' => 'submit',
'form' => $form->createView() 'form' => $form->createView(),
]); ]);
} }
} }
public function info(Request $request) public function info(Request $request)
{ {
$info = $request->getSession()->get('registrationinfo'); $info = $request->getSession()->get('registrationinfo');
$mode = $request->getSession()->get('registrationmode'); $mode = $request->getSession()->get('registrationmode');
$redirectto = $request->getSession()->get('registrationredirectto'); $redirectto = $request->getSession()->get('registrationredirectto');
return $this->render($this->twig.'info.html.twig', [ return $this->render($this->twig.'info.html.twig', [
'useheader' => true, 'useheader' => true,
'usemenu' => false, 'usemenu' => false,
@ -367,25 +363,28 @@ class RegistrationController extends AbstractController
$appModeregistrationterme = $this->getParameter('appModeregistrationterme'); $appModeregistrationterme = $this->getParameter('appModeregistrationterme');
$appMasteridentity = $this->getParameter('appMasteridentity'); $appMasteridentity = $this->getParameter('appMasteridentity');
if($appModeregistrationterme=="none"||$appMasteridentity!="SQL") if ('none' == $appModeregistrationterme || 'SQL' != $appMasteridentity) {
throw $this->createAccessDeniedException('Permission denied'); throw $this->createAccessDeniedException('Permission denied');
}
// Initialisation de l'enregistrement // Initialisation de l'enregistrement
$data = $em->getRepository($this->entity)->find($id); $data = $em->getRepository($this->entity)->find($id);
if (!$data) throw $this->createNotFoundException('Unable to find entity.'); if (!$data) {
throw $this->createNotFoundException('Unable to find entity.');
}
// Controler les permissions // Controler les permissions
$this->canupdate($access, $data, $em); $this->canupdate($access, $data, $em);
// Création du formulaire // Création du formulaire
$form = $this->createForm(Form::class,$data,array( $form = $this->createForm(Form::class, $data, [
"mode"=>"update", 'mode' => 'update',
"access"=>$access, 'access' => $access,
"userid"=>$this->getUser()->getId(), 'userid' => $this->getUser()->getId(),
"appMasteridentity"=>$this->GetParameter("appMasteridentity"), 'appMasteridentity' => $this->GetParameter('appMasteridentity'),
"appNiveau01label"=>$this->GetParameter("appNiveau01label"), 'appNiveau01label' => $this->GetParameter('appNiveau01label'),
"appNiveau02label"=>$this->GetParameter("appNiveau02label"), 'appNiveau02label' => $this->GetParameter('appNiveau02label'),
)); ]);
// Récupération des data du formulaire // Récupération des data du formulaire
$form->handleRequest($request); $form->handleRequest($request);
@ -398,7 +397,7 @@ class RegistrationController extends AbstractController
$em->getManager()->flush(); $em->getManager()->flush();
// Retour à la liste // Retour à la liste
return $this->redirectToRoute(str_replace("_admin_","_".$access."_",$this->route)); return $this->redirectToRoute(str_replace('_admin_', '_'.$access.'_', $this->route));
} }
// Sur validation // Sur validation
@ -421,9 +420,9 @@ class RegistrationController extends AbstractController
$data->setStatut(2); $data->setStatut(2);
// Email à l'utilisateur // Email à l'utilisateur
$url = $this->generateUrl('app_registration_validation', array("key"=>$data->getKeyvalue()), UrlGeneratorInterface::ABSOLUTE_URL); $url = $this->generateUrl('app_registration_validation', ['key' => $data->getKeyvalue()], UrlGeneratorInterface::ABSOLUTE_URL);
$subject=$appname." : confirmation de validation"; $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>"; $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(); $to = $data->getEmail();
$from = $noreply; $from = $noreply;
$fromName = $appname; $fromName = $appname;
@ -433,7 +432,7 @@ class RegistrationController extends AbstractController
$em->getManager()->flush(); $em->getManager()->flush();
// Retour à la liste // Retour à la liste
return $this->redirectToRoute(str_replace("_admin_","_".$access."_",$this->route)); return $this->redirectToRoute(str_replace('_admin_', '_'.$access.'_', $this->route));
} }
// Affichage du formulaire // Affichage du formulaire
@ -444,7 +443,7 @@ class RegistrationController extends AbstractController
$this->data => $data, $this->data => $data,
'mode' => 'update', 'mode' => 'update',
'access' => $access, 'access' => $access,
'form' => $form->createView() 'form' => $form->createView(),
]); ]);
} }
@ -453,8 +452,9 @@ class RegistrationController extends AbstractController
$appmoderegistration = $this->getParameter('appModeregistration'); $appmoderegistration = $this->getParameter('appModeregistration');
$appMasteridentity = $this->getParameter('appMasteridentity'); $appMasteridentity = $this->getParameter('appMasteridentity');
if($appmoderegistration=="none"||$appMasteridentity!="SQL") if ('none' == $appmoderegistration || 'SQL' != $appMasteridentity) {
throw $this->createAccessDeniedException('Permission denied'); throw $this->createAccessDeniedException('Permission denied');
}
$now = new \DateTime(); $now = new \DateTime();
@ -463,30 +463,29 @@ class RegistrationController extends AbstractController
->from($this->entity, 'entity') ->from($this->entity, 'entity')
->where('entity.keyvalue= :key') ->where('entity.keyvalue= :key')
->andWhere('entity.keyexpire >= :date') ->andWhere('entity.keyexpire >= :date')
->setParameter("key", $key) ->setParameter('key', $key)
->setParameter("date", $now) ->setParameter('date', $now)
->getQuery() ->getQuery()
->getSingleResult(); ->getSingleResult();
if (!$data) { if (!$data) {
$info="Clé de validation invalide"; $info = 'Clé de validation invalide';
$mode="danger"; $mode = 'danger';
$request->getSession()->set('registrationinfo', $info); $request->getSession()->set('registrationinfo', $info);
$request->getSession()->set('registrationmode', $mode); $request->getSession()->set('registrationmode', $mode);
$request->getSession()->set('registrationredirectto', null); $request->getSession()->set('registrationredirectto', null);
} } else {
else {
$url = $this->generateUrl('app_login'); $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>"; $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"; $mode = 'success';
$request->getSession()->set('registrationinfo', $info); $request->getSession()->set('registrationinfo', $info);
$request->getSession()->set('registrationmode', $mode); $request->getSession()->set('registrationmode', $mode);
// Initialisation de l'enregistrement // Initialisation de l'enregistrement
$user = new User(); $user = new User();
$user->setAvatar("noavatar.png"); $user->setAvatar('noavatar.png');
$user->setUsername($data->getUsername()); $user->setUsername($data->getUsername());
$user->setEmail($data->getEmail()); $user->setEmail($data->getEmail());
$user->setLastname($data->getLastname()); $user->setLastname($data->getLastname());
@ -505,7 +504,7 @@ class RegistrationController extends AbstractController
$user->setPostaladress($data->getPostaladress()); $user->setPostaladress($data->getPostaladress());
$user->setJob($data->getJob()); $user->setJob($data->getJob());
$user->setPosition($data->getPosition()); $user->setPosition($data->getPosition());
$user->setRoles(["ROLE_USER"]); $user->setRoles(['ROLE_USER']);
// Sauvegarde // Sauvegarde
$em->getManager()->persist($user); $em->getManager()->persist($user);
@ -519,66 +518,68 @@ class RegistrationController extends AbstractController
return $this->redirectToRoute('app_registration_info'); return $this->redirectToRoute('app_registration_info');
} }
public function delete($id, $access, Request $request, ManagerRegistry $em) public function delete($id, $access, Request $request, ManagerRegistry $em)
{ {
// Récupération de l'enregistrement courant // Récupération de l'enregistrement courant
$data = $em->getRepository($this->entity)->find($id); $data = $em->getRepository($this->entity)->find($id);
if (!$data) throw $this->createNotFoundException('Unable to find entity.'); if (!$data) {
throw $this->createNotFoundException('Unable to find entity.');
}
// Controler les permissions // Controler les permissions
$this->candelete($access, $data, $em); $this->candelete($access, $data, $em);
// Tentative de suppression // Tentative de suppression
try { try {
$em->getManager()->remove($data); $em->getManager()->remove($data);
$em->getManager()->flush(); $em->getManager()->flush();
} } catch (\Exception $e) {
catch (\Exception $e) { $request->getSession()->getFlashBag()->add('error', $e->getMessage());
$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).'_update', ['id' => $id]);
} }
return $this->redirectToRoute(str_replace("_admin_","_".$access."_",$this->route)); return $this->redirectToRoute(str_replace('_admin_', '_'.$access.'_', $this->route));
} }
public function resetpwd01(Request $request, ManagerRegistry $em) public function resetpwd01(Request $request, ManagerRegistry $em)
{ {
$appmoderegistration = $this->getParameter('appModeregistration'); $appmoderegistration = $this->getParameter('appModeregistration');
$appMasteridentity = $this->getParameter('appMasteridentity'); $appMasteridentity = $this->getParameter('appMasteridentity');
if($appMasteridentity!="SQL") if ('SQL' != $appMasteridentity) {
throw $this->createAccessDeniedException('Permission denied'); throw $this->createAccessDeniedException('Permission denied');
}
// Création du formulaire // Création du formulaire
$form = $this->createForm(ResetpwdType::class,null,array("mode"=>"resetpwd01")); $form = $this->createForm(ResetpwdType::class, null, ['mode' => 'resetpwd01']);
// Récupération des data du formulaire // Récupération des data du formulaire
$form->handleRequest($request); $form->handleRequest($request);
$data = $form->getData(); $data = $form->getData();
if ($form->get('submit')->isClicked()) { if ($form->get('submit')->isClicked()) {
$user=$em->getRepository("App\Entity\User")->findOneby(["email"=>$data->getEmail()]); $user = $em->getRepository("App\Entity\User")->findOneby(['email' => $data->getEmail()]);
// On s'assure que le mail existe dans la base des utilisateurs // On s'assure que le mail existe dans la base des utilisateurs
if (!$user) { if (!$user) {
$request->getSession()->getFlashBag()->add("error", 'Mail inconnu'); $request->getSession()->getFlashBag()->add('error', 'Mail inconnu');
// Affichage du formulaire // Affichage du formulaire
dump("here"); dump('here');
return $this->render($this->twig.'resetpwd01.html.twig', [ return $this->render($this->twig.'resetpwd01.html.twig', [
'useheader' => true, 'useheader' => true,
'usemenu' => false, 'usemenu' => false,
'usesidebar' => false, 'usesidebar' => false,
'maxsize' => 1200, 'maxsize' => 1200,
'form' => $form->createView() 'form' => $form->createView(),
]); ]);
} }
} }
// Sur validation // Sur validation
if ($form->get('submit')->isClicked()) { if ($form->get('submit')->isClicked()) {
$user=$em->getRepository("App\Entity\User")->findOneby(["email"=>$data->getEmail()]); $user = $em->getRepository("App\Entity\User")->findOneby(['email' => $data->getEmail()]);
$appname = $request->getSession()->get('appname'); $appname = $request->getSession()->get('appname');
$noreply = $this->getParameter('appMailnoreply'); $noreply = $this->getParameter('appMailnoreply');
@ -596,17 +597,17 @@ class RegistrationController extends AbstractController
$em->getManager()->flush(); $em->getManager()->flush();
// Email au user // Email au user
$url = $this->generateUrl('app_resetpwd02', array("key"=>$user->getKeyvalue()), UrlGeneratorInterface::ABSOLUTE_URL); $url = $this->generateUrl('app_resetpwd02', ['key' => $user->getKeyvalue()], UrlGeneratorInterface::ABSOLUTE_URL);
$subject=$appname." : réinitialisation mot de passe"; $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>"; $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(); $to = $user->getEmail();
$from = $noreply; $from = $noreply;
$fromName = $appname; $fromName = $appname;
$this->mail->sendEmail($subject, $body, $to, $from, $fromName); $this->mail->sendEmail($subject, $body, $to, $from, $fromName);
// Info // Info
$info="Vous allez recevoir un mail avec lien qui vous permettra de réinitialiser votre mot de passe"; $info = 'Vous allez recevoir un mail avec lien qui vous permettra de réinitialiser votre mot de passe';
$mode="info"; $mode = 'info';
$request->getSession()->set('registrationinfo', $info); $request->getSession()->set('registrationinfo', $info);
$request->getSession()->set('registrationmode', $mode); $request->getSession()->set('registrationmode', $mode);
$request->getSession()->set('registrationredirectto', null); $request->getSession()->set('registrationredirectto', null);
@ -620,39 +621,40 @@ class RegistrationController extends AbstractController
'usemenu' => false, 'usemenu' => false,
'usesidebar' => false, 'usesidebar' => false,
'maxsize' => 1200, 'maxsize' => 1200,
'form' => $form->createView() 'form' => $form->createView(),
]); ]);
} }
public function resetpwd02($key, Request $request, ManagerRegistry $em) public function resetpwd02($key, Request $request, ManagerRegistry $em)
{ {
$appMasteridentity = $this->getParameter('appMasteridentity'); $appMasteridentity = $this->getParameter('appMasteridentity');
if($appMasteridentity!="SQL") if ('SQL' != $appMasteridentity) {
throw $this->createAccessDeniedException('Permission denied'); throw $this->createAccessDeniedException('Permission denied');
}
$now = new \DateTime(); $now = new \DateTime();
$user = $em->getManager()->createQueryBuilder() $user = $em->getManager()->createQueryBuilder()
->select('table') ->select('table')
->from("App:User",'table') ->from('App:User', 'table')
->where('table.keyvalue= :key') ->where('table.keyvalue= :key')
->andWhere('table.keyexpire >= :date') ->andWhere('table.keyexpire >= :date')
->setParameter("key", $key) ->setParameter('key', $key)
->setParameter("date", $now) ->setParameter('date', $now)
->getQuery() ->getQuery()
->getSingleResult(); ->getSingleResult();
if (!$user) { if (!$user) {
$info="Clé de validation invalide"; $info = 'Clé de validation invalide';
$mode="danger"; $mode = 'danger';
$request->getSession()->set('registrationinfo', $info); $request->getSession()->set('registrationinfo', $info);
$request->getSession()->set('registrationmode', $mode); $request->getSession()->set('registrationmode', $mode);
$request->getSession()->set('registrationredirectto', null); $request->getSession()->set('registrationredirectto', null);
return $this->redirectToRoute('app_registration_info'); return $this->redirectToRoute('app_registration_info');
} } else {
else {
// Création du formulaire // Création du formulaire
$form = $this->createForm(ResetpwdType::class,$user,array("mode"=>"resetpwd02")); $form = $this->createForm(ResetpwdType::class, $user, ['mode' => 'resetpwd02']);
// Récupération des data du formulaire // Récupération des data du formulaire
$form->handleRequest($request); $form->handleRequest($request);
@ -668,10 +670,11 @@ class RegistrationController extends AbstractController
$url = $this->generateUrl('app_login'); $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>"; $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"; $mode = 'success';
$request->getSession()->set('registrationinfo', $info); $request->getSession()->set('registrationinfo', $info);
$request->getSession()->set('registrationmode', $mode); $request->getSession()->set('registrationmode', $mode);
$request->getSession()->set('registrationredirectto', null); $request->getSession()->set('registrationredirectto', null);
return $this->redirectToRoute('app_registration_info'); return $this->redirectToRoute('app_registration_info');
} }
@ -681,57 +684,67 @@ class RegistrationController extends AbstractController
'usemenu' => false, 'usemenu' => false,
'usesidebar' => false, 'usesidebar' => false,
'maxsize' => 1200, 'maxsize' => 1200,
'form' => $form->createView() 'form' => $form->createView(),
]); ]);
} }
} }
private function canupdate($access,$entity,$em) { private function canupdate($access, $entity, $em)
{
switch ($access) { switch ($access) {
case "admin" : return true; break; case 'admin': return true;
case "modo" : break;
$usermodo=$em->getRepository("App\Entity\UserModo")->findOneBy(["user"=>$this->getUser(),"niveau01"=>$entity->getNiveau01()]); case 'modo':
if(!$usermodo) throw $this->createAccessDeniedException('Permission denied'); $usermodo = $em->getRepository("App\Entity\UserModo")->findOneBy(['user' => $this->getUser(), 'niveau01' => $entity->getNiveau01()]);
if (!$usermodo) {
throw $this->createAccessDeniedException('Permission denied');
}
return true; return true;
break; break;
} }
throw $this->createAccessDeniedException('Permission denied'); throw $this->createAccessDeniedException('Permission denied');
} }
private function candelete($access,$entity,$em) { private function candelete($access, $entity, $em)
{
switch ($access) { switch ($access) {
case "admin" : return true; break; case 'admin': return true;
case "modo" : break;
$usermodo=$em->getRepository("App\Entity\UserModo")->findOneBy(["user"=>$this->getUser(),"niveau01"=>$entity->getNiveau01()]); case 'modo':
if(!$usermodo) throw $this->createAccessDeniedException('Permission denied'); $usermodo = $em->getRepository("App\Entity\UserModo")->findOneBy(['user' => $this->getUser(), 'niveau01' => $entity->getNiveau01()]);
if (!$usermodo) {
throw $this->createAccessDeniedException('Permission denied');
}
return true; return true;
break; break;
} }
throw $this->createAccessDeniedException('Permission denied'); throw $this->createAccessDeniedException('Permission denied');
} }
protected function getErrorForm($id,$form,$request,$data,$mode,$idstatut,$em) { protected function getErrorForm($id, $form, $request, $data, $mode, $idstatut, $em)
if ($form->get('submit')->isClicked() && $mode=="submit") { {
if ($form->get('submit')->isClicked() && 'submit' == $mode) {
// Si validation par administrateur demander une motivation // Si validation par administrateur demander une motivation
$appmoderegistration = $this->getParameter('appModeregistration'); $appmoderegistration = $this->getParameter('appModeregistration');
if(is_null($data->getMotivation())&&$appmoderegistration=="BYADMIN") { if (is_null($data->getMotivation()) && 'BYADMIN' == $appmoderegistration) {
// On recherche le domaine du mail dans la liste blanche // On recherche le domaine du mail dans la liste blanche
$email=explode("@",$data->getEmail()); $email = explode('@', $data->getEmail());
$domaine = end($email); $domaine = end($email);
$whitelist = $em->getManager()->getRepository("App\Entity\Whitelist")->findBy(["label"=>$domaine]); $whitelist = $em->getManager()->getRepository("App\Entity\Whitelist")->findBy(['label' => $domaine]);
if(!$whitelist) 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")); $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()) { if ($form->get('submit')->isClicked() && !$form->isValid()) {
$errors = $form->getErrors(); $errors = $form->getErrors();
foreach ($errors as $error) { foreach ($errors as $error) {
$request->getSession()->getFlashBag()->add("error", $error->getMessage()); $request->getSession()->getFlashBag()->add('error', $error->getMessage());
$request->getSession()->getFlashBag()->add("error", $error->getMessage()); $request->getSession()->getFlashBag()->add('error', $error->getMessage());
} }
} }
} }
} }

View File

@ -2,11 +2,11 @@
namespace App\Controller; namespace App\Controller;
use Doctrine\Persistence\ManagerRegistry;
use FOS\RestBundle\Controller\AbstractFOSRestController; use FOS\RestBundle\Controller\AbstractFOSRestController;
use Symfony\Component\HttpFoundation\Request;
use FOS\RestBundle\Controller\Annotations as FOSRest; use FOS\RestBundle\Controller\Annotations as FOSRest;
use OpenApi\Annotations as OA; use OpenApi\Annotations as OA;
use Doctrine\Persistence\ManagerRegistry; use Symfony\Component\HttpFoundation\Request;
class RestController extends AbstractFOSRestController class RestController extends AbstractFOSRestController
{ {
@ -14,8 +14,7 @@ class RestController extends AbstractFOSRestController
private $cpt; private $cpt;
/** /**
* getAllUsers * getAllUsers.
*
* *
* @FOSRest\Get("/rest/getAllUsers") * @FOSRest\Get("/rest/getAllUsers")
* @OA\Response( * @OA\Response(
@ -31,16 +30,15 @@ class RestController extends AbstractFOSRestController
* @OA\Schema(type="string") * @OA\Schema(type="string")
* ) * )
*/ */
public function getAllUsers(Request $request, ManagerRegistry $em)
{
public function getAllUsers(Request $request,ManagerRegistry $em) {
set_time_limit(0); set_time_limit(0);
ini_set('memory_limit', '1024M'); ini_set('memory_limit', '1024M');
// Récupération des parametres // Récupération des parametres
if(!$this->iskey($request->headers->get("key"))) { if (!$this->iskey($request->headers->get('key'))) {
$view = $this->view("API Key inconnue", 403); $view = $this->view('API Key inconnue', 403);
return $this->handleView($view); return $this->handleView($view);
} }
@ -51,13 +49,12 @@ class RestController extends AbstractFOSRestController
} }
$view = $this->view($output, 200); $view = $this->view($output, 200);
return $this->handleView($view); return $this->handleView($view);
} }
/** /**
* getOneUser * getOneUser.
*
* *
* @FOSRest\Get("/rest/getOneUser") * @FOSRest\Get("/rest/getOneUser")
* @OA\Response( * @OA\Response(
@ -80,34 +77,34 @@ class RestController extends AbstractFOSRestController
* @OA\Schema(type="string") * @OA\Schema(type="string")
* ) * )
*/ */
public function getOneUser(Request $request, ManagerRegistry $em)
{
public function getOneUser(Request $request,ManagerRegistry $em) {
set_time_limit(0); set_time_limit(0);
ini_set('memory_limit', '1024M'); ini_set('memory_limit', '1024M');
// Récupération des parametres // Récupération des parametres
if(!$this->iskey($request->headers->get("key"))) { if (!$this->iskey($request->headers->get('key'))) {
$view = $this->view("API Key inconnue", 403); $view = $this->view('API Key inconnue', 403);
return $this->handleView($view); return $this->handleView($view);
} }
$output = []; $output = [];
$user=$em->getRepository("App\Entity\User")->findOneBy(["username"=>$request->headers->get("login")]); $user = $em->getRepository("App\Entity\User")->findOneBy(['username' => $request->headers->get('login')]);
if (!$user) { if (!$user) {
$view = $this->view("Utilisateur inconnue", 403); $view = $this->view('Utilisateur inconnue', 403);
return $this->handleView($view); return $this->handleView($view);
} }
$output = $this->userFormat($user); $output = $this->userFormat($user);
$view = $this->view($output, 200); $view = $this->view($output, 200);
return $this->handleView($view); return $this->handleView($view);
} }
/** /**
* getAllNiveau01s * getAllNiveau01s.
*
* *
* @FOSRest\Get("/rest/getAllNiveau01s") * @FOSRest\Get("/rest/getAllNiveau01s")
* @OA\Response( * @OA\Response(
@ -123,16 +120,15 @@ class RestController extends AbstractFOSRestController
* @OA\Schema(type="string") * @OA\Schema(type="string")
* ) * )
*/ */
public function getAllNiveau01s(Request $request, ManagerRegistry $em)
{
public function getAllNiveau01s(Request $request,ManagerRegistry $em) {
set_time_limit(0); set_time_limit(0);
ini_set('memory_limit', '1024M'); ini_set('memory_limit', '1024M');
// Récupération des parametres // Récupération des parametres
if(!$this->iskey($request->headers->get("key"))) { if (!$this->iskey($request->headers->get('key'))) {
$view = $this->view("API Key inconnue", 403); $view = $this->view('API Key inconnue', 403);
return $this->handleView($view); return $this->handleView($view);
} }
@ -143,12 +139,12 @@ class RestController extends AbstractFOSRestController
} }
$view = $this->view($output, 200); $view = $this->view($output, 200);
return $this->handleView($view); return $this->handleView($view);
} }
/** /**
* getOneNiveau01 * getOneNiveau01.
*
* *
* @FOSRest\Get("/rest/getOneNiveau01") * @FOSRest\Get("/rest/getOneNiveau01")
* @OA\Response( * @OA\Response(
@ -171,34 +167,34 @@ class RestController extends AbstractFOSRestController
* @OA\Schema(type="string") * @OA\Schema(type="string")
* ) * )
*/ */
public function getOneNiveau01(Request $request, ManagerRegistry $em)
{
public function getOneNiveau01(Request $request,ManagerRegistry $em) {
set_time_limit(0); set_time_limit(0);
ini_set('memory_limit', '1024M'); ini_set('memory_limit', '1024M');
// Récupération des parametres // Récupération des parametres
if(!$this->iskey($request->headers->get("key"))) { if (!$this->iskey($request->headers->get('key'))) {
$view = $this->view("API Key inconnue", 403); $view = $this->view('API Key inconnue', 403);
return $this->handleView($view); return $this->handleView($view);
} }
$output = []; $output = [];
$niveau01=$em->getRepository("App\Entity\Niveau01")->findOneBy(["label"=>$request->headers->get("label")]); $niveau01 = $em->getRepository("App\Entity\Niveau01")->findOneBy(['label' => $request->headers->get('label')]);
if (!$niveau01) { if (!$niveau01) {
$view = $this->view("Niveau01 inconnu", 403); $view = $this->view('Niveau01 inconnu', 403);
return $this->handleView($view); return $this->handleView($view);
} }
$output = $this->niveau01Format($niveau01, true); $output = $this->niveau01Format($niveau01, true);
$view = $this->view($output, 200); $view = $this->view($output, 200);
return $this->handleView($view); return $this->handleView($view);
} }
/** /**
* getAllNiveau02s * getAllNiveau02s.
*
* *
* @FOSRest\Get("/rest/getAllNiveau02s") * @FOSRest\Get("/rest/getAllNiveau02s")
* @OA\Response( * @OA\Response(
@ -214,16 +210,15 @@ class RestController extends AbstractFOSRestController
* @OA\Schema(type="string") * @OA\Schema(type="string")
* ) * )
*/ */
public function getAllNiveau02s(Request $request, ManagerRegistry $em)
{
public function getAllNiveau02s(Request $request,ManagerRegistry $em) {
set_time_limit(0); set_time_limit(0);
ini_set('memory_limit', '1024M'); ini_set('memory_limit', '1024M');
// Récupération des parametres // Récupération des parametres
if(!$this->iskey($request->headers->get("key"))) { if (!$this->iskey($request->headers->get('key'))) {
$view = $this->view("API Key inconnue", 403); $view = $this->view('API Key inconnue', 403);
return $this->handleView($view); return $this->handleView($view);
} }
@ -234,12 +229,12 @@ class RestController extends AbstractFOSRestController
} }
$view = $this->view($output, 200); $view = $this->view($output, 200);
return $this->handleView($view); return $this->handleView($view);
} }
/** /**
* getOneNiveau02 * getOneNiveau02.
*
* *
* @FOSRest\Get("/rest/getOneNiveau02") * @FOSRest\Get("/rest/getOneNiveau02")
* @OA\Response( * @OA\Response(
@ -262,34 +257,34 @@ class RestController extends AbstractFOSRestController
* @OA\Schema(type="string") * @OA\Schema(type="string")
* ) * )
*/ */
public function getOneNiveau02(Request $request, ManagerRegistry $em)
{
public function getOneNiveau02(Request $request,ManagerRegistry $em) {
set_time_limit(0); set_time_limit(0);
ini_set('memory_limit', '1024M'); ini_set('memory_limit', '1024M');
// Récupération des parametres // Récupération des parametres
if(!$this->iskey($request->headers->get("key"))) { if (!$this->iskey($request->headers->get('key'))) {
$view = $this->view("API Key inconnue", 403); $view = $this->view('API Key inconnue', 403);
return $this->handleView($view); return $this->handleView($view);
} }
$output = []; $output = [];
$niveau02=$em->getRepository("App\Entity\Niveau02")->findOneBy(["label"=>$request->headers->get("label")]); $niveau02 = $em->getRepository("App\Entity\Niveau02")->findOneBy(['label' => $request->headers->get('label')]);
if (!$niveau02) { if (!$niveau02) {
$view = $this->view("Niveau02 inconnu", 403); $view = $this->view('Niveau02 inconnu', 403);
return $this->handleView($view); return $this->handleView($view);
} }
$output = $this->niveau02Format($niveau02, true); $output = $this->niveau02Format($niveau02, true);
$view = $this->view($output, 200); $view = $this->view($output, 200);
return $this->handleView($view); return $this->handleView($view);
} }
/** /**
* getAllGroups * getAllGroups.
*
* *
* @FOSRest\Get("/rest/getAllGroups") * @FOSRest\Get("/rest/getAllGroups")
* @OA\Response( * @OA\Response(
@ -305,33 +300,34 @@ class RestController extends AbstractFOSRestController
* @OA\Schema(type="string") * @OA\Schema(type="string")
* ) * )
*/ */
public function getAllGroups(Request $request, ManagerRegistry $em)
{
public function getAllGroups(Request $request,ManagerRegistry $em) {
set_time_limit(0); set_time_limit(0);
ini_set('memory_limit', '1024M'); ini_set('memory_limit', '1024M');
// Récupération des parametres // Récupération des parametres
if(!$this->iskey($request->headers->get("key"))) { if (!$this->iskey($request->headers->get('key'))) {
$view = $this->view("API Key inconnue", 403); $view = $this->view('API Key inconnue', 403);
return $this->handleView($view); return $this->handleView($view);
} }
$output = []; $output = [];
$groups = $em->getRepository("App\Entity\Group")->findAll(); $groups = $em->getRepository("App\Entity\Group")->findAll();
foreach ($groups as $group) { foreach ($groups as $group) {
if($group->getId()<0) continue; if ($group->getId() < 0) {
continue;
}
array_push($output, $this->groupFormat($group, true)); array_push($output, $this->groupFormat($group, true));
} }
$view = $this->view($output, 200); $view = $this->view($output, 200);
return $this->handleView($view); return $this->handleView($view);
} }
/** /**
* getOneGroup * getOneGroup.
*
* *
* @FOSRest\Get("/rest/getOneGroup") * @FOSRest\Get("/rest/getOneGroup")
* @OA\Response( * @OA\Response(
@ -354,114 +350,131 @@ class RestController extends AbstractFOSRestController
* @OA\Schema(type="string") * @OA\Schema(type="string")
* ) * )
*/ */
public function getOneGroup(Request $request, ManagerRegistry $em)
{
public function getOneGroup(Request $request,ManagerRegistry $em) {
set_time_limit(0); set_time_limit(0);
ini_set('memory_limit', '1024M'); ini_set('memory_limit', '1024M');
// Récupération des parametres // Récupération des parametres
if(!$this->iskey($request->headers->get("key"))) { if (!$this->iskey($request->headers->get('key'))) {
$view = $this->view("API Key inconnue", 403); $view = $this->view('API Key inconnue', 403);
return $this->handleView($view); return $this->handleView($view);
} }
$output = []; $output = [];
$group=$em->getRepository("App\Entity\Group")->findOneBy(["label"=>$request->headers->get("label")]); $group = $em->getRepository("App\Entity\Group")->findOneBy(['label' => $request->headers->get('label')]);
if (!$group) { if (!$group) {
$view = $this->view("Group inconnu", 403); $view = $this->view('Group inconnu', 403);
return $this->handleView($view); return $this->handleView($view);
} }
$output = $this->groupFormat($group, true); $output = $this->groupFormat($group, true);
$view = $this->view($output, 200); $view = $this->view($output, 200);
return $this->handleView($view); return $this->handleView($view);
} }
private function iskey($key)
{
return $key == $this->getParameter('appSecret');
private function iskey($key) {
return ($key==$this->getParameter("appSecret"));
} }
private function userFormat($user) { private function userFormat($user)
{
$output = []; $output = [];
$output["userid"]=$user->getId(); $output['userid'] = $user->getId();
$output["userlogin"]=$user->getUsername(); $output['userlogin'] = $user->getUsername();
$output["userlastname"]=$user->getLastname(); $output['userlastname'] = $user->getLastname();
$output["userfirstname"]=$user->getFirstname(); $output['userfirstname'] = $user->getFirstname();
$output["useremail"]=$user->getEmail(); $output['useremail'] = $user->getEmail();
$output["userjob"]=$user->getJob(); $output['userjob'] = $user->getJob();
$output["userposition"]=$user->getPosition(); $output['userposition'] = $user->getPosition();
$output["userpostaladress"]=$user->getPostaladress(); $output['userpostaladress'] = $user->getPostaladress();
$output["usertelephonenumber"]=$user->getTelephonenumber(); $output['usertelephonenumber'] = $user->getTelephonenumber();
$output["useravatar"]="https://".str_replace("//","/",$this->getParameter("appWeburl").$this->getParameter("appAlias").$this->generateUrl('app_minio_image',["file"=>"avatar/".$user->getAvatar()],true)); $output['useravatar'] = 'https://'.str_replace('//', '/', $this->getParameter('appWeburl').$this->getParameter('appAlias').$this->generateUrl('app_minio_image', ['file' => 'avatar/'.$user->getAvatar()], true));
$output["userniveau01"]=$this->niveau01Format($user->getNiveau01()); $output['userniveau01'] = $this->niveau01Format($user->getNiveau01());
$output["userniveau02"]=$this->niveau02Format($user->getNiveau02()); $output['userniveau02'] = $this->niveau02Format($user->getNiveau02());
$output["usergroups"]=[]; $output['usergroups'] = [];
foreach ($user->getGroups() as $usergroup) { foreach ($user->getGroups() as $usergroup) {
$groupFormat = $this->groupFormat($usergroup->getGroup()); $groupFormat = $this->groupFormat($usergroup->getGroup());
if($groupFormat) array_push($output["usergroups"],$groupFormat); if ($groupFormat) {
array_push($output['usergroups'], $groupFormat);
} }
if(empty($output["usergroups"])) $output["usergroups"]=null; }
if (empty($output['usergroups'])) {
$output['usergroups'] = null;
}
return $output; return $output;
} }
private function niveau01Format($niveau01,$withmembers=false){ private function niveau01Format($niveau01, $withmembers = false)
if(!$niveau01) return null; {
if (!$niveau01) {
return null;
}
$output = []; $output = [];
$output["niveau01id"]=$niveau01->getId(); $output['niveau01id'] = $niveau01->getId();
$output["niveau01label"]=$niveau01->getLabel(); $output['niveau01label'] = $niveau01->getLabel();
if ($withmembers) { if ($withmembers) {
$output["niveau01users"]=[]; $output['niveau01users'] = [];
foreach ($niveau01->getUsers() as $user) { foreach ($niveau01->getUsers() as $user) {
array_push($output["niveau01users"],["userid"=>$user->getId(),"userlogin"=>$user->getUsername()]); array_push($output['niveau01users'], ['userid' => $user->getId(), 'userlogin' => $user->getUsername()]);
}
if (empty($output['niveau01users'])) {
$output['niveau01users'] = null;
} }
if(empty($output["niveau01users"])) $output["niveau01users"]=null;
} }
return $output; return $output;
} }
private function niveau02Format($niveau02,$withmembers=false){ private function niveau02Format($niveau02, $withmembers = false)
if(!$niveau02) return null; {
if (!$niveau02) {
return null;
}
$output = []; $output = [];
$output["niveau02id"]=$niveau02->getId(); $output['niveau02id'] = $niveau02->getId();
$output["niveau02label"]=$niveau02->getLabel(); $output['niveau02label'] = $niveau02->getLabel();
if ($withmembers) { if ($withmembers) {
$output["niveau02niveau01"]=$this->niveau01Format($niveau02->getNiveau01()); $output['niveau02niveau01'] = $this->niveau01Format($niveau02->getNiveau01());
$output["niveau02users"]=[]; $output['niveau02users'] = [];
foreach ($niveau02->getUsers() as $user) { foreach ($niveau02->getUsers() as $user) {
array_push($output["niveau02users"],["userid"=>$user->getId(),"userlogin"=>$user->getUsername()]); array_push($output['niveau02users'], ['userid' => $user->getId(), 'userlogin' => $user->getUsername()]);
}
if (empty($output['niveau02users'])) {
$output['niveau02users'] = null;
} }
if(empty($output["niveau02users"])) $output["niveau02users"]=null;
} }
return $output; return $output;
} }
private function groupFormat($group,$withmembers=false){ private function groupFormat($group, $withmembers = false)
if(!$group||$group->getId()<0) return null; {
if (!$group || $group->getId() < 0) {
return null;
}
$output = []; $output = [];
$output["groupid"]=$group->getId(); $output['groupid'] = $group->getId();
$output["grouplabel"]=$group->getLabel(); $output['grouplabel'] = $group->getLabel();
if ($withmembers) { if ($withmembers) {
$output["groupusers"]=[]; $output['groupusers'] = [];
foreach ($group->getUsers() as $usergroup) { foreach ($group->getUsers() as $usergroup) {
array_push($output["groupusers"],["userid"=>$usergroup->getUser()->getId(),"userlogin"=>$usergroup->getUser()->getUsername()]); array_push($output['groupusers'], ['userid' => $usergroup->getUser()->getId(), 'userlogin' => $usergroup->getUser()->getUsername()]);
}
if (empty($output['groupusers'])) {
$output['groupusers'] = null;
} }
if(empty($output["groupusers"])) $output["groupusers"]=null;
} }
return $output; return $output;
} }
} }

View File

@ -2,24 +2,23 @@
namespace App\Controller; 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\Entity\Group;
use App\Entity\Niveau01;
use App\Entity\User;
use App\Form\LoginType; use App\Form\LoginType;
use App\Service\LdapService;
use App\Service\ApiService; use App\Service\ApiService;
use App\Service\LdapService;
use Doctrine\Persistence\ManagerRegistry;
use Ramsey\Uuid\Uuid;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
class SecurityController extends AbstractController class SecurityController extends AbstractController
{ {
@ -39,27 +38,27 @@ class SecurityController extends AbstractController
public function noperm(Request $request) public function noperm(Request $request)
{ {
return $this->render('Home/noperm.html.twig', [ return $this->render('Home/noperm.html.twig', [
"useheader"=>true, 'useheader' => true,
"usemenu"=>false, 'usemenu' => false,
]); ]);
} }
public function login(Request $request, AuthenticationUtils $authenticationUtils, ManagerRegistry $em) public function login(Request $request, AuthenticationUtils $authenticationUtils, ManagerRegistry $em)
{ {
switch($this->getParameter("appAuth")) { switch ($this->getParameter('appAuth')) {
case "SQL": case 'SQL':
return $this->loginSQL($request, $authenticationUtils, $em); return $this->loginSQL($request, $authenticationUtils, $em);
break; break;
case "CAS": case 'CAS':
return $this->loginCAS($request, $authenticationUtils, $em); return $this->loginCAS($request, $authenticationUtils, $em);
break; break;
case "LDAP": case 'LDAP':
return $this->loginLDAP($request, $authenticationUtils, $em); return $this->loginLDAP($request, $authenticationUtils, $em);
break; break;
case "OPENID": case 'OPENID':
return $this->loginOPENID($request, $authenticationUtils, $em); return $this->loginOPENID($request, $authenticationUtils, $em);
break; break;
} }
@ -67,27 +66,26 @@ class SecurityController extends AbstractController
public function loginSQL(Request $request, AuthenticationUtils $authenticationUtils, ManagerRegistry $em) public function loginSQL(Request $request, AuthenticationUtils $authenticationUtils, ManagerRegistry $em)
{ {
return $this->render('Home/loginSQL.html.twig', array( return $this->render('Home/loginSQL.html.twig', [
'last_username' => $authenticationUtils->getLastUsername(), 'last_username' => $authenticationUtils->getLastUsername(),
'error' => $authenticationUtils->getLastAuthenticationError(), 'error' => $authenticationUtils->getLastAuthenticationError(),
)); ]);
} }
public function loginCAS(Request $request, AuthenticationUtils $authenticationUtils, ManagerRegistry $em) public function loginCAS(Request $request, AuthenticationUtils $authenticationUtils, ManagerRegistry $em)
{ {
// Récupération de la cible de navigation // Récupération de la cible de navigation
$redirect = $request->getSession()->get("_security.main.target_path"); $redirect = $request->getSession()->get('_security.main.target_path');
// Masteridentity // Masteridentity
$appMasteridentity=$this->getParameter("appMasteridentity"); $appMasteridentity = $this->getParameter('appMasteridentity');
// Init Client CAS // Init Client CAS
$alias = $this->getParameter('appAlias'); $alias = $this->getParameter('appAlias');
\phpCAS::setDebug($this->appKernel->getProjectDir()."/var/log/cas.log"); \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::client(CAS_VERSION_2_0, $this->getParameter('casHost'), intval($this->getParameter('casPort')), is_null($this->getParameter('casPath')) ? '' : $this->getParameter('casPath'), false);
\phpCAS::setNoCasServerValidation(); \phpCAS::setNoCasServerValidation();
// Authentification // Authentification
\phpCAS::forceAuthentication(); \phpCAS::forceAuthentication();
@ -100,45 +98,49 @@ class SecurityController extends AbstractController
// Init // Init
$email = "$username@nomail.fr"; $email = "$username@nomail.fr";
$lastname = $username; $lastname = $username;
$firstname = " "; $firstname = ' ';
$avatar="noavatar.png"; $avatar = 'noavatar.png';
// Rechercher l'utilisateur // Rechercher l'utilisateur
if(isset($attributes[$this->getParameter('casUsername')])) if (isset($attributes[$this->getParameter('casUsername')])) {
$username = $attributes[$this->getParameter('casUsername')]; $username = $attributes[$this->getParameter('casUsername')];
}
if(isset($attributes[$this->getParameter('casEmail')])) if (isset($attributes[$this->getParameter('casEmail')])) {
$email = $attributes[$this->getParameter('casEmail')]; $email = $attributes[$this->getParameter('casEmail')];
}
if(isset($attributes[$this->getParameter('casLastname')])) if (isset($attributes[$this->getParameter('casLastname')])) {
$lastname = $attributes[$this->getParameter('casLastname')]; $lastname = $attributes[$this->getParameter('casLastname')];
}
if(isset($attributes[$this->getParameter('casFirstname')])) if (isset($attributes[$this->getParameter('casFirstname')])) {
$firstname = $attributes[$this->getParameter('casFirstname')]; $firstname = $attributes[$this->getParameter('casFirstname')];
}
if(isset($attributes[$this->getParameter('casAvatar')])) if (isset($attributes[$this->getParameter('casAvatar')])) {
$avatar = $attributes[$this->getParameter('casAvatar')]; $avatar = $attributes[$this->getParameter('casAvatar')];
}
// Rechercher l'utilisateur // Rechercher l'utilisateur
$user = $em->getRepository('App\Entity\User')->findOneBy(array("username"=>$username)); $user = $em->getRepository('App\Entity\User')->findOneBy(['username' => $username]);
if (!$user) { if (!$user) {
if(!$this->getParameter("casAutosubmit")) return $this->redirect($this->generateUrl('app_noperm')); if (!$this->getParameter('casAutosubmit')) {
return $this->redirect($this->generateUrl('app_noperm'));
}
$this->submitSSONiveau01($attributes, $em); $this->submitSSONiveau01($attributes, $em);
$this->submitSSOGroup($attributes, $em); $this->submitSSOGroup($attributes, $em);
$niveau01 = $em->getRepository('App\Entity\Niveau01')->calculateSSONiveau01($attributes); $niveau01 = $em->getRepository('App\Entity\Niveau01')->calculateSSONiveau01($attributes);
$user = $this->submituser($username, $firstname, $lastname, $email, $avatar, $niveau01, $em); $user = $this->submituser($username, $firstname, $lastname, $email, $avatar, $niveau01, $em);
$user = $em->getRepository('App\Entity\Group')->calculateSSOGroup($user, $attributes); $user = $em->getRepository('App\Entity\Group')->calculateSSOGroup($user, $attributes);
} } elseif ($this->getParameter('casAutoupdate')) {
elseif($this->getParameter("casAutoupdate")) {
$this->submitSSONiveau01($attributes, $em); $this->submitSSONiveau01($attributes, $em);
$this->submitSSOGroup($attributes, $em); $this->submitSSOGroup($attributes, $em);
$this->updateuser($user, $firstname, $lastname, $email, $avatar, $em); $this->updateuser($user, $firstname, $lastname, $email, $avatar, $em);
$user = $em->getRepository('App\Entity\Group')->calculateSSOGroup($user, $attributes); $user = $em->getRepository('App\Entity\Group')->calculateSSOGroup($user, $attributes);
} }
// Autoconnexion // Autoconnexion
return $this->autoconnexion($user, $redirect, $request); return $this->autoconnexion($user, $redirect, $request);
} }
@ -152,22 +154,21 @@ class SecurityController extends AbstractController
$form->handleRequest($request); $form->handleRequest($request);
// Affichage du formulaire // Affichage du formulaire
return $this->render("Home/loginLDAP.html.twig", [ return $this->render('Home/loginLDAP.html.twig', [
"useheader"=>false, 'useheader' => false,
"usemenu"=>false, 'usemenu' => false,
"usesidebar"=>false, 'usesidebar' => false,
"form"=>$form->createView(), 'form' => $form->createView(),
]); ]);
} }
public function loginldapcheck(Request $request, AuthenticationUtils $authenticationUtils, ManagerRegistry $em) public function loginldapcheck(Request $request, AuthenticationUtils $authenticationUtils, ManagerRegistry $em)
{ {
$username = $request->get('login')['username'];
$username=$request->get('login')["username"]; $password = $request->get('login')['password'];
$password=$request->get('login')["password"];
// Récupération de la cible de navigation // Récupération de la cible de navigation
$redirect = $request->getSession()->get("_security.main.target_path"); $redirect = $request->getSession()->get('_security.main.target_path');
// L'utilisateur se co à l'annuaire // L'utilisateur se co à l'annuaire
$userldap = $this->ldapservice->userconnect($username, $password); $userldap = $this->ldapservice->userconnect($username, $password);
@ -177,30 +178,35 @@ class SecurityController extends AbstractController
// Init // Init
$email = "$username@nomail.fr"; $email = "$username@nomail.fr";
$lastname = $username; $lastname = $username;
$firstname = " "; $firstname = ' ';
$avatar="noavatar.png"; $avatar = 'noavatar.png';
// Rechercher l'utilisateur // Rechercher l'utilisateur
if(isset($userldap[$this->getParameter('ldapFirstname')])) if (isset($userldap[$this->getParameter('ldapFirstname')])) {
$firstname = $userldap[$this->getParameter('ldapFirstname')]; $firstname = $userldap[$this->getParameter('ldapFirstname')];
}
if(isset($userldap[$this->getParameter('ldapLastname')])) if (isset($userldap[$this->getParameter('ldapLastname')])) {
$lastname = $userldap[$this->getParameter('ldapLastname')]; $lastname = $userldap[$this->getParameter('ldapLastname')];
}
if(isset($userldap[$this->getParameter('ldapEmail')])) if (isset($userldap[$this->getParameter('ldapEmail')])) {
$email = $userldap[$this->getParameter('ldapEmail')]; $email = $userldap[$this->getParameter('ldapEmail')];
}
if(isset($userldap[$this->getParameter('ldapAvatar')])) if (isset($userldap[$this->getParameter('ldapAvatar')])) {
$avatar = $userldap[$this->getParameter('ldapAvatar')]; $avatar = $userldap[$this->getParameter('ldapAvatar')];
}
$user = $em->getRepository('App\Entity\User')->findOneBy(array("username"=>$username)); $user = $em->getRepository('App\Entity\User')->findOneBy(['username' => $username]);
if (!$user) { if (!$user) {
if(!$this->getParameter("ldapAutosubmit")) return $this->redirect($this->generateUrl('app_noperm')); if (!$this->getParameter('ldapAutosubmit')) {
return $this->redirect($this->generateUrl('app_noperm'));
}
$niveau01 = $em->getRepository('App\Entity\Niveau01')->calculateLDAPNiveau01($username); $niveau01 = $em->getRepository('App\Entity\Niveau01')->calculateLDAPNiveau01($username);
$user = $this->submituser($username, $firstname, $lastname, $email, $avatar, $niveau01, $em); $user = $this->submituser($username, $firstname, $lastname, $email, $avatar, $niveau01, $em);
} } elseif ($this->getParameter('ldapAutoupdate')) {
elseif($this->getParameter("ldapAutoupdate")) {
$this->updateuser($user, $firstname, $lastname, $email, $avatar, $em); $this->updateuser($user, $firstname, $lastname, $email, $avatar, $em);
} }
@ -211,85 +217,95 @@ class SecurityController extends AbstractController
return $this->redirect($this->generateUrl('app_login')); return $this->redirect($this->generateUrl('app_login'));
} }
public function loginOPENID(Request $request, AuthenticationUtils $authenticationUtils, ManagerRegistry $em) public function loginOPENID(Request $request, AuthenticationUtils $authenticationUtils, ManagerRegistry $em)
{ {
$state = Uuid::uuid4(); $state = Uuid::uuid4();
$request->getSession()->set("oauthState",$state); $request->getSession()->set('oauthState', $state);
$callback=$this->generateUrl('app_loginopenidcallback', array(), UrlGeneratorInterface::ABSOLUTE_URL); $callback = $this->generateUrl('app_loginopenidcallback', [], UrlGeneratorInterface::ABSOLUTE_URL);
$url=$this->getParameter("oauthLoginurl")."?client_id=".$this->getParameter("oauthClientid")."&redirect_uri=".$callback."&response_type=code&state=".$state."&scope=openid"; $url = $this->getParameter('oauthLoginurl').'?client_id='.$this->getParameter('oauthClientid').'&redirect_uri='.$callback.'&response_type=code&state='.$state.'&scope=openid';
return $this->redirect($url); return $this->redirect($url);
} }
public function loginopenidcallback(Request $request, AuthenticationUtils $authenticationUtils, ManagerRegistry $em) public function loginopenidcallback(Request $request, AuthenticationUtils $authenticationUtils, ManagerRegistry $em)
{ {
// Récupération de la cible de navigation // Récupération de la cible de navigation
$redirect = $request->getSession()->get("_security.main.target_path"); $redirect = $request->getSession()->get('_security.main.target_path');
// Masteridentity // Masteridentity
$appMasteridentity=$this->getParameter("appMasteridentity"); $appMasteridentity = $this->getParameter('appMasteridentity');
$callback=$this->generateUrl('app_loginopenidcallback', array(), UrlGeneratorInterface::ABSOLUTE_URL); $callback = $this->generateUrl('app_loginopenidcallback', [], UrlGeneratorInterface::ABSOLUTE_URL);
$apiurl = $this->getParameter("oauthTokenurl"); $apiurl = $this->getParameter('oauthTokenurl');
$query = [ $query = [
"grant_type" => "authorization_code", 'grant_type' => 'authorization_code',
"code" => $request->get("code"), 'code' => $request->get('code'),
"redirect_uri" => $callback, 'redirect_uri' => $callback,
"client_id" => $this->getParameter("oauthClientid"), 'client_id' => $this->getParameter('oauthClientid'),
"client_secret" => $this->getParameter("oauthClientsecret"), 'client_secret' => $this->getParameter('oauthClientsecret'),
]; ];
$response=$this->apiservice->run("POST",$apiurl,$query,null,"form"); $response = $this->apiservice->run('POST', $apiurl, $query, null, 'form');
if(!$response||$response->code!="200") die("pb openid 01"); if (!$response || '200' != $response->code) {
exit('pb openid 01');
}
$accesstoken = $response->body->access_token; $accesstoken = $response->body->access_token;
$accesstokentype = $response->body->token_type; $accesstokentype = $response->body->token_type;
$îdtoken = $response->body->id_token; $îdtoken = $response->body->id_token;
$request->getSession()->set("oauthAccesstoken",$accesstoken); $request->getSession()->set('oauthAccesstoken', $accesstoken);
$request->getSession()->set("oauthIdtoken",$îdtoken); $request->getSession()->set('oauthIdtoken', $îdtoken);
$apiurl = $this->getParameter("oauthUserinfo"); $apiurl = $this->getParameter('oauthUserinfo');
$response=$this->apiservice->run("GET",$apiurl,null,["Authorization"=>$accesstokentype." ".$accesstoken]); $response = $this->apiservice->run('GET', $apiurl, null, ['Authorization' => $accesstokentype.' '.$accesstoken]);
if(!$response||$response->code!="200") die("pb openid 02"); if (!$response || '200' != $response->code) {
exit('pb openid 02');
}
$attributes = json_decode(json_encode($response->body), true); $attributes = json_decode(json_encode($response->body), true);
// Username // Username
$username=""; $username = '';
if(isset($attributes[$this->getParameter('oauthUsername')])) if (isset($attributes[$this->getParameter('oauthUsername')])) {
$username = $attributes[$this->getParameter('oauthUsername')]; $username = $attributes[$this->getParameter('oauthUsername')];
}
// Valeur par défaut // Valeur par défaut
$email = "$username@nomail.fr"; $email = "$username@nomail.fr";
$lastname = $username; $lastname = $username;
$firstname = " "; $firstname = ' ';
$avatar="noavatar.png"; $avatar = 'noavatar.png';
// Récupérer les attributs associés // Récupérer les attributs associés
if(isset($attributes[$this->getParameter('oauthEmail')])) if (isset($attributes[$this->getParameter('oauthEmail')])) {
$email = $attributes[$this->getParameter('oauthEmail')]; $email = $attributes[$this->getParameter('oauthEmail')];
}
if(isset($attributes[$this->getParameter('oauthLastname')])) if (isset($attributes[$this->getParameter('oauthLastname')])) {
$lastname = $attributes[$this->getParameter('oauthLastname')]; $lastname = $attributes[$this->getParameter('oauthLastname')];
}
if(isset($attributes[$this->getParameter('oauthFirstname')])) if (isset($attributes[$this->getParameter('oauthFirstname')])) {
$firstname = $attributes[$this->getParameter('oauthFirstname')]; $firstname = $attributes[$this->getParameter('oauthFirstname')];
}
if(isset($attributes[$this->getParameter('oauthAvatar')])) if (isset($attributes[$this->getParameter('oauthAvatar')])) {
$avatar = $attributes[$this->getParameter('oauthAvatar')]; $avatar = $attributes[$this->getParameter('oauthAvatar')];
}
// Rechercher l'utilisateur // Rechercher l'utilisateur
$user = $em->getRepository('App\Entity\User')->findOneBy(array("username"=>$username)); $user = $em->getRepository('App\Entity\User')->findOneBy(['username' => $username]);
if (!$user) { if (!$user) {
if(!$this->getParameter("oauthAutosubmit")) return $this->redirect($this->generateUrl('app_noperm')); if (!$this->getParameter('oauthAutosubmit')) {
return $this->redirect($this->generateUrl('app_noperm'));
}
$this->submitSSONiveau01($attributes, $em); $this->submitSSONiveau01($attributes, $em);
$this->submitSSOGroup($attributes, $em); $this->submitSSOGroup($attributes, $em);
$niveau01 = $em->getRepository('App\Entity\Niveau01')->calculateSSONiveau01($attributes); $niveau01 = $em->getRepository('App\Entity\Niveau01')->calculateSSONiveau01($attributes);
$user = $this->submituser($username, $firstname, $lastname, $email, $avatar, $niveau01, $em); $user = $this->submituser($username, $firstname, $lastname, $email, $avatar, $niveau01, $em);
} } elseif ($this->getParameter('oauthAutoupdate')) {
elseif($this->getParameter("oauthAutoupdate")) {
$this->submitSSONiveau01($attributes, $em); $this->submitSSONiveau01($attributes, $em);
$this->submitSSOGroup($attributes, $em); $this->submitSSOGroup($attributes, $em);
$this->updateuser($user, $firstname, $lastname, $email, $avatar, $em); $this->updateuser($user, $firstname, $lastname, $email, $avatar, $em);
@ -300,83 +316,91 @@ class SecurityController extends AbstractController
return $this->autoconnexion($user, $redirect, $request); return $this->autoconnexion($user, $redirect, $request);
} }
public function logout(Request $request) { public function logout(Request $request)
$auth_mode=$this->getParameter("appAuth"); {
$auth_mode = $this->getParameter('appAuth');
switch ($auth_mode) { switch ($auth_mode) {
case "SQL": case 'SQL':
return $this->logoutSQL($request); return $this->logoutSQL($request);
break; break;
case "CAS": case 'CAS':
return $this->logoutCAS($request); return $this->logoutCAS($request);
break; break;
case "LDAP": case 'LDAP':
return $this->logoutLDAP($request); return $this->logoutLDAP($request);
break; break;
case "OPENID": case 'OPENID':
return $this->logoutOPENID($request); return $this->logoutOPENID($request);
break; break;
} }
} }
public function logoutSQL(Request $request) { public function logoutSQL(Request $request)
{
$this->tokenstorage->setToken(null); $this->tokenstorage->setToken(null);
$request->getSession()->invalidate(); $request->getSession()->invalidate();
return $this->redirect($this->generateUrl("app_home"));
return $this->redirect($this->generateUrl('app_home'));
} }
public function logoutCAS(Request $request) { public function logoutCAS(Request $request)
{
$this->tokenstorage->setToken(null); $this->tokenstorage->setToken(null);
$request->getSession()->invalidate(); $request->getSession()->invalidate();
// Init Client CAS // Init Client CAS
$alias = $this->getParameter('appAlias'); $alias = $this->getParameter('appAlias');
\phpCAS::setDebug($this->appKernel->getProjectDir()."/var/log/cas.log"); \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::client(CAS_VERSION_2_0, $this->getParameter('casHost'), intval($this->getParameter('casPort')), is_null($this->getParameter('casPath')) ? '' : $this->getParameter('casPath'), false);
\phpCAS::setNoCasServerValidation(); \phpCAS::setNoCasServerValidation();
// Logout // Logout
$url=$this->generateUrl('app_home', array(), UrlGeneratorInterface::ABSOLUTE_URL); $url = $this->generateUrl('app_home', [], UrlGeneratorInterface::ABSOLUTE_URL);
\phpCAS::logout(array("service"=>$url)); \phpCAS::logout(['service' => $url]);
return true; return true;
} }
public function logoutLDAP(Request $request) { public function logoutLDAP(Request $request)
{
$this->tokenstorage->setToken(null); $this->tokenstorage->setToken(null);
$request->getSession()->invalidate(); $request->getSession()->invalidate();
return $this->redirect($this->generateUrl("app_home"));
return $this->redirect($this->generateUrl('app_home'));
} }
public function logoutOPENID(Request $request)
public function logoutOPENID(Request $request) { {
$accesstoken=$request->getSession()->get("oauthAccesstoken"); $accesstoken = $request->getSession()->get('oauthAccesstoken');
$idtoken=$request->getSession()->get("oauthIdtoken"); $idtoken = $request->getSession()->get('oauthIdtoken');
$state=$request->getSession()->get("oauthState"); $state = $request->getSession()->get('oauthState');
$this->tokenstorage->setToken(null); $this->tokenstorage->setToken(null);
$request->getSession()->invalidate(); $request->getSession()->invalidate();
$url=$this->getParameter("oauthLogouturl"); $url = $this->getParameter('oauthLogouturl');
if ($url) { if ($url) {
$callback=($request->isSecure()?"https://":"http://").str_replace("//","/",$this->getParameter("appWeburl").$this->getParameter("appAlias").$this->generateUrl('app_home')); $callback = ($request->isSecure() ? 'https://' : 'http://').str_replace('//', '/', $this->getParameter('appWeburl').$this->getParameter('appAlias').$this->generateUrl('app_home'));
$callback = substr($callback, 0, -1); $callback = substr($callback, 0, -1);
$url .= "?id_token_hint=$idtoken&scope=openid&post_logout_redirect_uri=$callback"; $url .= "?id_token_hint=$idtoken&scope=openid&post_logout_redirect_uri=$callback";
return $this->redirect($url);
} else return $this->redirect($this->generateUrl("app_home")); return $this->redirect($url);
} else {
return $this->redirect($this->generateUrl('app_home'));
}
} }
// Génération automatique des niveau01 provenant de l'attribut casniveau01 // Génération automatique des niveau01 provenant de l'attribut casniveau01
private function submitSSONiveau01($attributes,ManagerRegistry $em) { private function submitSSONiveau01($attributes, ManagerRegistry $em)
$attrNiveau01=($this->getParameter("appAuth")=="CAS"?$this->getParameter('casNiveau01'):$this->getParameter('oauthNiveau01')); {
if(!$attrNiveau01) $attrNiveau01 = ('CAS' == $this->getParameter('appAuth') ? $this->getParameter('casNiveau01') : $this->getParameter('oauthNiveau01'));
if (!$attrNiveau01) {
return null; return null;
}
// Si l'utilisateur possège l'attribut niveau01 dans ses attributs // Si l'utilisateur possège l'attribut niveau01 dans ses attributs
if (array_key_exists($attrNiveau01, $attributes)) { if (array_key_exists($attrNiveau01, $attributes)) {
@ -387,17 +411,17 @@ class SecurityController extends AbstractController
foreach ($attributes[$attrNiveau01] as $ssoniveau01) { foreach ($attributes[$attrNiveau01] as $ssoniveau01) {
$basedn = $this->getParameter('ldapBasedn'); $basedn = $this->getParameter('ldapBasedn');
$name = $ssoniveau01; $name = $ssoniveau01;
if($basedn!="") { 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 // 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) { if (false !== stripos($name, $basedn)) {
$tbname=explode(",",$name); $tbname = explode(',', $name);
$tbname=explode("=",$tbname[0]); $tbname = explode('=', $tbname[0]);
$name = $tbname[1]; $name = $tbname[1];
} }
} }
// Recherche du groupe // Recherche du groupe
$niveau01=$em->getRepository("App\Entity\Niveau01")->findOneBy(["label"=>$name]); $niveau01 = $em->getRepository("App\Entity\Niveau01")->findOneBy(['label' => $name]);
if (!$niveau01) { if (!$niveau01) {
$niveau01 = new Niveau01(); $niveau01 = new Niveau01();
$niveau01->setLabel($name); $niveau01->setLabel($name);
@ -411,12 +435,13 @@ class SecurityController extends AbstractController
} }
} }
// Génération automatique des groupes provenant de l'attribut casgroup ou oauthgroup // Génération automatique des groupes provenant de l'attribut casgroup ou oauthgroup
private function submitSSOGroup($attributes,ManagerRegistry $em) { private function submitSSOGroup($attributes, ManagerRegistry $em)
$attrGroup=($this->getParameter("appAuth")=="CAS"?$this->getParameter('casGroup'):$this->getParameter('oauthGroup')); {
if(!$attrGroup) $attrGroup = ('CAS' == $this->getParameter('appAuth') ? $this->getParameter('casGroup') : $this->getParameter('oauthGroup'));
if (!$attrGroup) {
return null; return null;
}
// Si l'utilisateur possège l'attribut groupe dans ses attributs // Si l'utilisateur possège l'attribut groupe dans ses attributs
if (array_key_exists($attrGroup, $attributes)) { if (array_key_exists($attrGroup, $attributes)) {
@ -427,17 +452,17 @@ class SecurityController extends AbstractController
foreach ($attributes[$attrGroup] as $ssogroup) { foreach ($attributes[$attrGroup] as $ssogroup) {
$basedn = $this->getParameter('ldapBasedn'); $basedn = $this->getParameter('ldapBasedn');
$name = $ssogroup; $name = $ssogroup;
if($basedn!="") { 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 // 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) { if (false !== stripos($name, $basedn)) {
$tbname=explode(",",$name); $tbname = explode(',', $name);
$tbname=explode("=",$tbname[0]); $tbname = explode('=', $tbname[0]);
$name = $tbname[1]; $name = $tbname[1];
} }
} }
// Recherche du groupe // Recherche du groupe
$group=$em->getRepository("App\Entity\Group")->findOneBy(["label"=>$name]); $group = $em->getRepository("App\Entity\Group")->findOneBy(['label' => $name]);
if (!$group) { if (!$group) {
$group = new Group(); $group = new Group();
$group->setLabel($name); $group->setLabel($name);
@ -453,16 +478,27 @@ class SecurityController extends AbstractController
} }
} }
private function submituser($username,$firstname,$lastname,$email,$avatar,$niveau01,$em) { 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($email)) {
if(empty($firstname)) $firstname = " "; $email = $username.'@nomail.com';
if(empty($lastname)) $lastname = $username; }
if (empty($avatar)) {
$avatar = 'noavatar.png';
}
if (empty($firstname)) {
$firstname = ' ';
}
if (empty($lastname)) {
$lastname = $username;
}
$uuid = Uuid::uuid4(); $uuid = Uuid::uuid4();
$password=$this->getParameter("appAuth")."PWD-".$username."-".$uuid; $password = $this->getParameter('appAuth').'PWD-'.$username.'-'.$uuid;
// Si aucun niveau01 on prend par défaut le niveau system // Si aucun niveau01 on prend par défaut le niveau system
if(!$niveau01) $niveau01=$em->getRepository('App\Entity\Niveau01')->find(-1); if (!$niveau01) {
$niveau01 = $em->getRepository('App\Entity\Niveau01')->find(-1);
}
// Autogénération du user vu qu'il a pu se connecter // Autogénération du user vu qu'il a pu se connecter
$user = new User(); $user = new User();
@ -478,10 +514,11 @@ class SecurityController extends AbstractController
$user->setAvatar($avatar); $user->setAvatar($avatar);
$user->setIsvisible(true); $user->setIsvisible(true);
$user->setRole("ROLE_USER"); $user->setRole('ROLE_USER');
if(in_array($username,$this->getParameter("appAdmins"))) if (in_array($username, $this->getParameter('appAdmins'))) {
$user->setRole("ROLE_ADMIN"); $user->setRole('ROLE_ADMIN');
}
$em->getManager()->persist($user); $em->getManager()->persist($user);
$em->getManager()->flush(); $em->getManager()->flush();
@ -489,16 +526,28 @@ class SecurityController extends AbstractController
return $user; return $user;
} }
private function updateuser($user,$firstname,$lastname,$email,$avatar,$em) { private function updateuser($user, $firstname, $lastname, $email, $avatar, $em)
if($avatar=="noavatar.png") $avatar=$user->getAvatar(); {
if ('noavatar.png' == $avatar) {
$avatar = $user->getAvatar();
}
if(!empty($lastname)) $user->setLastname($lastname); if (!empty($lastname)) {
if(!empty($firstname)) $user->setFirstname($firstname); $user->setLastname($lastname);
if(!empty($email)) $user->setEmail($email); }
if(!empty($avatar)) $user->setAvatar($avatar); 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"))) if (in_array($user->getUsername(), $this->getParameter('appAdmins'))) {
$user->setRole("ROLE_ADMIN"); $user->setRole('ROLE_ADMIN');
}
$em->getManager()->flush(); $em->getManager()->flush();
} }
@ -506,7 +555,7 @@ class SecurityController extends AbstractController
private function autoconnexion($user, $redirect, Request $request) private function autoconnexion($user, $redirect, Request $request)
{ {
// Récupérer le token de l'utilisateur // Récupérer le token de l'utilisateur
$token = new UsernamePasswordToken($user, "main", $user->getRoles()); $token = new UsernamePasswordToken($user, 'main', $user->getRoles());
$this->tokenstorage->setToken($token); $this->tokenstorage->setToken($token);
$request->getSession()->set('_security_main', serialize($token)); $request->getSession()->set('_security_main', serialize($token));
@ -516,9 +565,10 @@ class SecurityController extends AbstractController
$dispatcher->dispatch($event); $dispatcher->dispatch($event);
// Redirection // Redirection
if($redirect) if ($redirect) {
return $this->redirect($redirect); return $this->redirect($redirect);
else } else {
return $this->redirect($this->generateUrl('app_home')); return $this->redirect($this->generateUrl('app_home'));
} }
} }
}

View File

@ -1,11 +1,12 @@
<?php <?php
namespace App\Controller; namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Yaml\Yaml;
use Doctrine\Persistence\ManagerRegistry; use Doctrine\Persistence\ManagerRegistry;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Finder\Finder;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Yaml\Yaml;
class ThemeController extends AbstractController class ThemeController extends AbstractController
{ {
@ -13,25 +14,25 @@ class ThemeController extends AbstractController
{ {
$finder = new Finder(); $finder = new Finder();
$dir = $this->getParameter('kernel.project_dir')."/public/themes"; $dir = $this->getParameter('kernel.project_dir').'/public/themes';
$url=$this->getParameter('appAlias')."themes"; $url = $this->getParameter('appAlias').'themes';
$finder->in($dir)->directories()->depth('== 0'); $finder->in($dir)->directories()->depth('== 0');
$themes = []; $themes = [];
$themes[""]["dir"]=""; $themes['']['dir'] = '';
$themes[""]["url"]=$url; $themes['']['url'] = $url;
$themes[""]["name"]="Thème par défaut"; $themes['']['name'] = 'Thème par défaut';
foreach ($finder as $file) { foreach ($finder as $file) {
$key = $file->getRelativePathname(); $key = $file->getRelativePathname();
$themes[$key]["dir"]=$key; $themes[$key]['dir'] = $key;
$themes[$key]["url"]=$url."/".$key; $themes[$key]['url'] = $url.'/'.$key;
$yml = Yaml::parseFile($dir.'/'.$key.'/info.yml'); $yml = Yaml::parseFile($dir.'/'.$key.'/info.yml');
$themes[$key]["name"]=$yml["name"]; $themes[$key]['name'] = $yml['name'];
} }
$current=$request->getSession()->get("apptheme"); $current = $request->getSession()->get('apptheme');
$currentheme = $themes[$current]; $currentheme = $themes[$current];
unset($themes[$current]); unset($themes[$current]);
@ -39,17 +40,17 @@ class ThemeController extends AbstractController
'useheader' => true, 'useheader' => true,
'usesidebar' => true, 'usesidebar' => true,
'currentheme' => $currentheme, 'currentheme' => $currentheme,
'themes' => $themes 'themes' => $themes,
]); ]);
} }
public function select($name, Request $request, ManagerRegistry $em) public function select($name, Request $request, ManagerRegistry $em)
{ {
$config=$em->getRepository("App\Entity\Config")->findoneBy(["id"=>"apptheme"]); $config = $em->getRepository("App\Entity\Config")->findoneBy(['id' => 'apptheme']);
$config->setValue($name); $config->setValue($name);
$em->getManager()->flush(); $em->getManager()->flush();
return $this->redirectToRoute("app_admin_theme"); return $this->redirectToRoute('app_admin_theme');
} }
} }

View File

@ -1,37 +1,36 @@
<?php <?php
namespace App\Controller; 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\User as Entity;
use App\Entity\UserGroup; use App\Entity\UserGroup;
use App\Entity\UserModo; use App\Entity\UserModo;
use App\Form\UserType as Form; use App\Form\UserType as Form;
use Doctrine\Persistence\ManagerRegistry;
use Ramsey\Uuid\Uuid;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class UserController extends AbstractController class UserController extends AbstractController
{ {
private $data="user"; private $data = 'user';
private $entity = "App\Entity\User"; private $entity = "App\Entity\User";
private $twig="User/"; private $twig = 'User/';
private $route="app_admin_user"; private $route = 'app_admin_user';
public function list($access, Request $request): Response public function list($access, Request $request): Response
{ {
if($access=="user"&&!$request->getSession()->get("showannuaire")) if ('user' == $access && !$request->getSession()->get('showannuaire')) {
throw $this->createAccessDeniedException('Permission denied'); throw $this->createAccessDeniedException('Permission denied');
}
return $this->render($this->twig.'list.html.twig', [ return $this->render($this->twig.'list.html.twig', [
"useheader"=>true, 'useheader' => true,
"usemenu"=>false, 'usemenu' => false,
"usesidebar"=>($access!="user"), 'usesidebar' => ('user' != $access),
"access"=>$access 'access' => $access,
]); ]);
} }
@ -49,18 +48,18 @@ class UserController extends AbstractController
// Nombre total d'enregistrement // Nombre total d'enregistrement
switch ($access) { switch ($access) {
case "admin": case 'admin':
$total = $em->getManager()->createQueryBuilder()->select('COUNT(entity)')->from($this->entity, 'entity')->getQuery()->getSingleScalarResult(); $total = $em->getManager()->createQueryBuilder()->select('COUNT(entity)')->from($this->entity, 'entity')->getQuery()->getSingleScalarResult();
break; break;
case "modo": case 'modo':
$total = $em->getManager()->createQueryBuilder() $total = $em->getManager()->createQueryBuilder()
->select('COUNT(entity)') ->select('COUNT(entity)')
->from($this->entity, 'entity') ->from($this->entity, 'entity')
->from("App\Entity\UserModo", 'usermodo') ->from("App\Entity\UserModo", 'usermodo')
->where("usermodo.niveau01 = entity.niveau01") ->where('usermodo.niveau01 = entity.niveau01')
->andWhere("usermodo.user = :user") ->andWhere('usermodo.user = :user')
->setParameter("user", $this->getUser()) ->setParameter('user', $this->getUser())
->getQuery()->getSingleScalarResult(); ->getQuery()->getSingleScalarResult();
break; break;
@ -69,13 +68,13 @@ class UserController extends AbstractController
$niveau02 = $this->getUser()->getNiveau02(); $niveau02 = $this->getUser()->getNiveau02();
$qb = $em->getManager()->createQueryBuilder()->select('COUNT(entity)')->from($this->entity, 'entity')->where('entity.isvisible=true'); $qb = $em->getManager()->createQueryBuilder()->select('COUNT(entity)')->from($this->entity, 'entity')->where('entity.isvisible=true');
switch($request->getSession()->get("scopeannu")) { switch ($request->getSession()->get('scopeannu')) {
case "SAME_NIVEAU01": case 'SAME_NIVEAU01':
$qb->andWhere("entity.niveau01 = :niveau01")->setParameter("niveau01",$niveau01); $qb->andWhere('entity.niveau01 = :niveau01')->setParameter('niveau01', $niveau01);
break; break;
case "SAME_NIVEAU02": case 'SAME_NIVEAU02':
$qb->andWhere("entity.niveau02 = :niveau02")->setParameter("niveau02",$niveau02); $qb->andWhere('entity.niveau02 = :niveau02')->setParameter('niveau02', $niveau02);
break; break;
} }
@ -84,34 +83,34 @@ class UserController extends AbstractController
} }
// Nombre d'enregistrement filtré // Nombre d'enregistrement filtré
if(!$search||$search["value"]=="") if (!$search || '' == $search['value']) {
$totalf = $total; $totalf = $total;
else { } else {
switch ($access) { switch ($access) {
case "admin": case 'admin':
$totalf = $em->getManager()->createQueryBuilder() $totalf = $em->getManager()->createQueryBuilder()
->select('COUNT(entity)') ->select('COUNT(entity)')
->from($this->entity, 'entity') ->from($this->entity, 'entity')
->from('App:Niveau01', 'niveau01') ->from('App:Niveau01', 'niveau01')
->where('entity.niveau01=niveau01.id') ->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('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"]."%") ->setParameter('value', '%'.$search['value'].'%')
->getQuery() ->getQuery()
->getSingleScalarResult(); ->getSingleScalarResult();
break; break;
case "modo": case 'modo':
$totalf = $em->getManager()->createQueryBuilder() $totalf = $em->getManager()->createQueryBuilder()
->select('COUNT(entity)') ->select('COUNT(entity)')
->from($this->entity, 'entity') ->from($this->entity, 'entity')
->from('App:Niveau01', 'niveau01') ->from('App:Niveau01', 'niveau01')
->from("App:UserModo",'usermodo') ->from('App:UserModo', 'usermodo')
->where('entity.niveau01=niveau01.id') ->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('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.niveau01 = entity.niveau01')
->andWhere("usermodo.user = :userid") ->andWhere('usermodo.user = :userid')
->setParameter("value", "%".$search["value"]."%") ->setParameter('value', '%'.$search['value'].'%')
->setParameter("userid", $this->getUser()->getId()) ->setParameter('userid', $this->getUser()->getId())
->getQuery() ->getQuery()
->getSingleScalarResult(); ->getSingleScalarResult();
break; break;
@ -124,15 +123,15 @@ class UserController extends AbstractController
->where('entity.niveau01=niveau01.id') ->where('entity.niveau01=niveau01.id')
->andWhere('entity.isvisible=true') ->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') ->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"]."%"); ->setParameter('value', '%'.$search['value'].'%');
switch($request->getSession()->get("scopeannu")) { switch ($request->getSession()->get('scopeannu')) {
case "SAME_NIVEAU01": case 'SAME_NIVEAU01':
$qb->andWhere("entity.niveau01 = :niveau01")->setParameter("niveau01",$niveau01); $qb->andWhere('entity.niveau01 = :niveau01')->setParameter('niveau01', $niveau01);
break; break;
case "SAME_NIVEAU02": case 'SAME_NIVEAU02':
$qb->andWhere("entity.niveau02 = :niveau02")->setParameter("niveau02",$niveau02); $qb->andWhere('entity.niveau02 = :niveau02')->setParameter('niveau02', $niveau02);
break; break;
} }
@ -142,27 +141,27 @@ class UserController extends AbstractController
} }
// Construction du tableau de retour // Construction du tableau de retour
$output = array( $output = [
'draw' => $draw, 'draw' => $draw,
'recordsFiltered' => $totalf, 'recordsFiltered' => $totalf,
'recordsTotal' => $total, 'recordsTotal' => $total,
'data' => array(), 'data' => [],
); ];
// Parcours des Enregistrement // Parcours des Enregistrement
$qb = $em->getManager()->createQueryBuilder(); $qb = $em->getManager()->createQueryBuilder();
switch ($access) { switch ($access) {
case "admin": case 'admin':
$qb->select('entity')->from($this->entity, 'entity')->from('App:Niveau01', 'niveau01'); $qb->select('entity')->from($this->entity, 'entity')->from('App:Niveau01', 'niveau01');
$qb->where('entity.niveau01=niveau01.id'); $qb->where('entity.niveau01=niveau01.id');
break; break;
case "modo": case 'modo':
$qb->select('entity')->from($this->entity,'entity')->from('App:Niveau01','niveau01')->from("App:UserModo",'usermodo'); $qb->select('entity')->from($this->entity, 'entity')->from('App:Niveau01', 'niveau01')->from('App:UserModo', 'usermodo');
$qb->where('entity.niveau01=niveau01.id'); $qb->where('entity.niveau01=niveau01.id');
$qb->andWhere("usermodo.niveau01 = entity.niveau01"); $qb->andWhere('usermodo.niveau01 = entity.niveau01');
$qb->andWhere("usermodo.user = :userid"); $qb->andWhere('usermodo.user = :userid');
$qb->setParameter("userid", $this->getUser()->getId()); $qb->setParameter('userid', $this->getUser()->getId());
break; break;
default: default:
@ -170,25 +169,25 @@ class UserController extends AbstractController
$qb->where('entity.niveau01=niveau01.id'); $qb->where('entity.niveau01=niveau01.id');
$qb->andWhere('entity.isvisible=true'); $qb->andWhere('entity.isvisible=true');
switch($request->getSession()->get("scopeannu")) { switch ($request->getSession()->get('scopeannu')) {
case "SAME_NIVEAU01": case 'SAME_NIVEAU01':
$qb->andWhere("entity.niveau01 = :niveau01")->setParameter("niveau01",$niveau01); $qb->andWhere('entity.niveau01 = :niveau01')->setParameter('niveau01', $niveau01);
break; break;
case "SAME_NIVEAU02": case 'SAME_NIVEAU02':
$qb->andWhere("entity.niveau02 = :niveau02")->setParameter("niveau02",$niveau02); $qb->andWhere('entity.niveau02 = :niveau02')->setParameter('niveau02', $niveau02);
break; break;
} }
break; break;
} }
if($search&&$search["value"]!="") { 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') $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"]."%"); ->setParameter('value', '%'.$search['value'].'%');
} }
if ($ordercolumn) { if ($ordercolumn) {
if($access=="admin"||$access=="modo") { if ('admin' == $access || 'modo' == $access) {
$ordercolumn = $ordercolumn - 1; $ordercolumn = $ordercolumn - 1;
} }
@ -231,45 +230,47 @@ class UserController extends AbstractController
foreach ($datas as $data) { foreach ($datas as $data) {
// Action // Action
$action = ""; $action = '';
switch ($access) { switch ($access) {
case "admin": 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>"; $action .= "<a href='".$this->generateUrl($this->route.'_update', ['id' => $data->getId()])."'><i class='fa fa-file fa-fw fa-2x'></i></a>";
break; break;
case "modo": 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>"; $action .= "<a href='".$this->generateUrl(str_replace('_admin_', '_modo_', $this->route).'_update', ['id' => $data->getId()])."'><i class='fa fa-file fa-fw fa-2x'></i></a>";
break; break;
} }
// Groupes // Groupes
$groups=""; $groups = '';
foreach ($data->getGroups() as $usergroup) { foreach ($data->getGroups() as $usergroup) {
$groups.=$usergroup->getGroup()->getLabel()."<br>"; $groups .= $usergroup->getGroup()->getLabel().'<br>';
} }
// Roles // Roles
$roles=""; $roles = '';
foreach ($data->getRoles() as $role) { foreach ($data->getRoles() as $role) {
$roles.=$role."<br>"; $roles .= $role.'<br>';
} }
$tmp=array(); $tmp = [];
if($access=="admin"||$access=="modo") array_push($tmp,$action); if ('admin' == $access || 'modo' == $access) {
array_push($tmp, $action);
}
array_push($tmp,"<img src='".$this->generateUrl('app_minio_image',["file"=>"avatar/".$data->getAvatar()])."' class='avatar'>"); array_push($tmp, "<img src='".$this->generateUrl('app_minio_image', ['file' => 'avatar/'.$data->getAvatar()])."' class='avatar'>");
array_push($tmp, $data->getUsername()); array_push($tmp, $data->getUsername());
array_push($tmp, $data->getLastname()); array_push($tmp, $data->getLastname());
array_push($tmp, $data->getFirstname()); array_push($tmp, $data->getFirstname());
array_push($tmp,"<a href='mailto:".$data->getEmail()."'>".$data->getEmail()."</a>"); array_push($tmp, "<a href='mailto:".$data->getEmail()."'>".$data->getEmail().'</a>');
array_push($tmp, $data->getTelephonenumber()); array_push($tmp, $data->getTelephonenumber());
array_push($tmp, $data->getNiveau01()->getLabel()); array_push($tmp, $data->getNiveau01()->getLabel());
array_push($tmp,($data->getNiveau02()?$data->getNiveau02()->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, $data->getVisitedate() ? $data->getVisitedate()->format('d/m/Y H:i').'<br>nb = '.$data->getVisitecpt() : '');
array_push($tmp, $roles); array_push($tmp, $roles);
array_push($tmp, $groups); array_push($tmp, $groups);
array_push($output["data"],$tmp); array_push($output['data'], $tmp);
} }
// Retour // Retour
@ -278,50 +279,52 @@ class UserController extends AbstractController
public function selectlist($access, Request $request, ManagerRegistry $em): Response public function selectlist($access, Request $request, ManagerRegistry $em): Response
{ {
$output=array(); $output = [];
$page_limit = $request->query->get('page_limit'); $page_limit = $request->query->get('page_limit');
$q = $request->query->get('q'); $q = $request->query->get('q');
$qb = $em->getManager()->createQueryBuilder(); $qb = $em->getManager()->createQueryBuilder();
$qb->select('entity')->from($this->entity, 'entity') $qb->select('entity')->from($this->entity, 'entity')
->where('entity.username LIKE :value') ->where('entity.username LIKE :value')
->setParameter("value", "%".$q."%") ->setParameter('value', '%'.$q.'%')
->orderBy('entity.username'); ->orderBy('entity.username');
$datas = $qb->setFirstResult(0)->setMaxResults($page_limit)->getQuery()->getResult(); $datas = $qb->setFirstResult(0)->setMaxResults($page_limit)->getQuery()->getResult();
foreach ($datas as $data) { foreach ($datas as $data) {
array_push($output,array("id"=>$data->getId(),"text"=>$data->getUsername())); array_push($output, ['id' => $data->getId(), 'text' => $data->getUsername()]);
} }
$ret_string["results"]=$output; $ret_string['results'] = $output;
$response = new JsonResponse($ret_string); $response = new JsonResponse($ret_string);
return $response; return $response;
} }
public function submit($access, Request $request, ManagerRegistry $em): Response public function submit($access, Request $request, ManagerRegistry $em): Response
{ {
// Vérifier que l'on puisse créer // Vérifier que l'on puisse créer
if($this->getParameter("appMasteridentity")!="SQL" && $this->getParameter("appSynchroPurgeUser")) if ('SQL' != $this->getParameter('appMasteridentity') && $this->getParameter('appSynchroPurgeUser')) {
throw $this->createNotFoundException('Permission denied'); throw $this->createNotFoundException('Permission denied');
}
// Controler les permissions // Controler les permissions
$this->cansubmit($access, $em); $this->cansubmit($access, $em);
// Initialisation de l'enregistrement // Initialisation de l'enregistrement
$data = new Entity(); $data = new Entity();
$data->setAvatar("noavatar.png"); $data->setAvatar('noavatar.png');
$data->setIsvisible(true); $data->setIsvisible(true);
$data->setApikey(Uuid::uuid4()); $data->setApikey(Uuid::uuid4());
// Création du formulaire // Création du formulaire
$form = $this->createForm(Form::class,$data,array( $form = $this->createForm(Form::class, $data, [
"mode"=>"submit", 'mode' => 'submit',
"access"=>$access, 'access' => $access,
"userid"=>$this->getUser()->getId(), 'userid' => $this->getUser()->getId(),
"appMasteridentity"=>$this->GetParameter("appMasteridentity"), 'appMasteridentity' => $this->GetParameter('appMasteridentity'),
"appNiveau01label"=>$this->GetParameter("appNiveau01label"), 'appNiveau01label' => $this->GetParameter('appNiveau01label'),
"appNiveau02label"=>$this->GetParameter("appNiveau02label"), 'appNiveau02label' => $this->GetParameter('appNiveau02label'),
)); ]);
// Récupération des data du formulaire // Récupération des data du formulaire
$form->handleRequest($request); $form->handleRequest($request);
@ -331,17 +334,15 @@ class UserController extends AbstractController
$data = $form->getData(); $data = $form->getData();
// S'assurer que les modos ne donne pas des ROLE_ADMIN ou ROLE_USER au user qu'il submit // S'assurer que les modos ne donne pas des ROLE_ADMIN ou ROLE_USER au user qu'il submit
if($access=="modo") { if ('modo' == $access) {
$roles = $data->getRoles(); $roles = $data->getRoles();
$roles=array_diff($roles,["ROLE_ADMIN","ROLE_MODO"]); $roles = array_diff($roles, ['ROLE_ADMIN', 'ROLE_MODO']);
$data->setRoles($roles); $data->setRoles($roles);
} }
// On récupère les groupes et on cacule ceux à ajouter ou à supprimer // On récupère les groupes et on cacule ceux à ajouter ou à supprimer
$lstgroups=array_filter(explode(",",$form->get("linkgroups")->getData())); $lstgroups = array_filter(explode(',', $form->get('linkgroups')->getData()));
$lstmodos=array_filter(explode(",",$form->get("linkmodos")->getData())); $lstmodos = array_filter(explode(',', $form->get('linkmodos')->getData()));
// Sauvegarde // Sauvegarde
$em->getManager()->persist($data); $em->getManager()->persist($data);
@ -350,7 +351,7 @@ class UserController extends AbstractController
// Ajout des groupes // Ajout des groupes
foreach ($lstgroups as $idgroup) { foreach ($lstgroups as $idgroup) {
$group = $em->getRepository("App\Entity\Group")->find($idgroup); $group = $em->getRepository("App\Entity\Group")->find($idgroup);
$usergroup=$em->getRepository('App\Entity\UserGroup')->findBy(["user"=>$data,"group"=>$group]); $usergroup = $em->getRepository('App\Entity\UserGroup')->findBy(['user' => $data, 'group' => $group]);
if (!$usergroup) { if (!$usergroup) {
$usergroup = new UserGroup(); $usergroup = new UserGroup();
$usergroup->setUser($data); $usergroup->setUser($data);
@ -366,7 +367,7 @@ class UserController extends AbstractController
// Ajout des modos // Ajout des modos
foreach ($lstmodos as $idmodo) { foreach ($lstmodos as $idmodo) {
$niveau01 = $em->getRepository("App\Entity\Niveau01")->find($idmodo); $niveau01 = $em->getRepository("App\Entity\Niveau01")->find($idmodo);
$usermodo=$em->getRepository('App\Entity\UserModo')->findBy(["user"=>$data,"niveau01"=>$niveau01]); $usermodo = $em->getRepository('App\Entity\UserModo')->findBy(['user' => $data, 'niveau01' => $niveau01]);
if (!$usermodo) { if (!$usermodo) {
$usermodo = new UserModo(); $usermodo = new UserModo();
$usermodo->setUser($data); $usermodo->setUser($data);
@ -378,26 +379,27 @@ class UserController extends AbstractController
} }
// Retour à la liste // Retour à la liste
return $this->redirectToRoute(str_replace("_admin_","_".$access."_",$this->route)); return $this->redirectToRoute(str_replace('_admin_', '_'.$access.'_', $this->route));
} }
// Affichage du formulaire // Affichage du formulaire
return $this->render($this->twig.'edit.html.twig', [ return $this->render($this->twig.'edit.html.twig', [
"useheader"=>true, 'useheader' => true,
"usemenu"=>false, 'usemenu' => false,
"usesidebar"=>true, 'usesidebar' => true,
"access"=>$access, 'access' => $access,
"mode"=>"submit", 'mode' => 'submit',
"form"=>$form->createView(), 'form' => $form->createView(),
$this->data => $data, $this->data => $data,
"listgroups"=>$this->getListGroups("admin",$em), 'listgroups' => $this->getListGroups('admin', $em),
"listmodos"=> $this->getListModos($em) 'listmodos' => $this->getListModos($em),
]); ]);
} }
public function profil($access, Request $request, ManagerRegistry $em): Response public function profil($access, Request $request, ManagerRegistry $em): Response
{ {
$id = $this->getUser()->getId(); $id = $this->getUser()->getId();
return $this->update($access, $id, $request, $em); return $this->update($access, $id, $request, $em);
} }
@ -405,7 +407,9 @@ class UserController extends AbstractController
{ {
// Initialisation de l'enregistrement // Initialisation de l'enregistrement
$data = $em->getRepository($this->entity)->find($id); $data = $em->getRepository($this->entity)->find($id);
if (!$data) throw $this->createNotFoundException('Unable to find entity.'); if (!$data) {
throw $this->createNotFoundException('Unable to find entity.');
}
// Controler les permissions // Controler les permissions
$this->canupdate($access, $data, $em); $this->canupdate($access, $data, $em);
@ -426,14 +430,14 @@ class UserController extends AbstractController
} }
// Création du formulaire // Création du formulaire
$form = $this->createForm(Form::class,$data,array( $form = $this->createForm(Form::class, $data, [
"mode"=>"update", 'mode' => 'update',
"access"=>$access, 'access' => $access,
"userid"=>$this->getUser()->getId(), 'userid' => $this->getUser()->getId(),
"appMasteridentity"=>$this->GetParameter("appMasteridentity"), 'appMasteridentity' => $this->GetParameter('appMasteridentity'),
"appNiveau01label"=>$this->GetParameter("appNiveau01label"), 'appNiveau01label' => $this->GetParameter('appNiveau01label'),
"appNiveau02label"=>$this->GetParameter("appNiveau02label"), 'appNiveau02label' => $this->GetParameter('appNiveau02label'),
)); ]);
// Récupération des data du formulaire // Récupération des data du formulaire
$form->handleRequest($request); $form->handleRequest($request);
@ -443,14 +447,14 @@ class UserController extends AbstractController
$data = $form->getData(); $data = $form->getData();
// S'assurer que les modos ne donne pas des ROLE_ADMIN ou ROLE_USER au user qu'il update // S'assurer que les modos ne donne pas des ROLE_ADMIN ou ROLE_USER au user qu'il update
if($access=="modo") { if ('modo' == $access) {
$roles = $data->getRoles(); $roles = $data->getRoles();
$roles=array_diff($roles,["ROLE_ADMIN","ROLE_MODO"]); $roles = array_diff($roles, ['ROLE_ADMIN', 'ROLE_MODO']);
$data->setRoles($roles); $data->setRoles($roles);
} }
// Si pas de changement de password on replace l'ancien // Si pas de changement de password on replace l'ancien
if($data->getPassword()=="") { if ('' == $data->getPassword()) {
$data->setPassword($oldpassword); $data->setPassword($oldpassword);
} }
// Sinon on encode le nouveau // Sinon on encode le nouveau
@ -462,14 +466,14 @@ class UserController extends AbstractController
$em->getManager()->flush(); $em->getManager()->flush();
// On récupère les groupes et on cacule ceux à ajouter ou à supprimer // On récupère les groupes et on cacule ceux à ajouter ou à supprimer
$lstgroups=array_filter(explode(",",$form->get("linkgroups")->getData())); $lstgroups = array_filter(explode(',', $form->get('linkgroups')->getData()));
$removegroups = array_diff($oldlstgroups, $lstgroups); $removegroups = array_diff($oldlstgroups, $lstgroups);
$addgroups = array_diff($lstgroups, $oldlstgroups); $addgroups = array_diff($lstgroups, $oldlstgroups);
// Ajout des nouveaux groupes // Ajout des nouveaux groupes
foreach ($addgroups as $idgroup) { foreach ($addgroups as $idgroup) {
$group = $em->getRepository("App\Entity\Group")->find($idgroup); $group = $em->getRepository("App\Entity\Group")->find($idgroup);
$usergroup=$em->getRepository('App\Entity\UserGroup')->findOneBy(["user"=>$data,"group"=>$group]); $usergroup = $em->getRepository('App\Entity\UserGroup')->findOneBy(['user' => $data, 'group' => $group]);
if (!$usergroup) { if (!$usergroup) {
$usergroup = new UserGroup(); $usergroup = new UserGroup();
$usergroup->setUser($data); $usergroup->setUser($data);
@ -484,7 +488,7 @@ class UserController extends AbstractController
// Suppression des groupes obsolètes // Suppression des groupes obsolètes
foreach ($removegroups as $idgroup) { foreach ($removegroups as $idgroup) {
$group = $em->getRepository("App\Entity\Group")->find($idgroup); $group = $em->getRepository("App\Entity\Group")->find($idgroup);
$usergroup=$em->getRepository('App\Entity\UserGroup')->findOneBy(["user"=>$data,"group"=>$group]); $usergroup = $em->getRepository('App\Entity\UserGroup')->findOneBy(['user' => $data, 'group' => $group]);
if ($usergroup) { if ($usergroup) {
$em->getManager()->remove($usergroup); $em->getManager()->remove($usergroup);
$em->getManager()->flush(); $em->getManager()->flush();
@ -492,15 +496,14 @@ class UserController extends AbstractController
} }
// On récupère les modos et on cacule ceux à ajouter ou à supprimer // On récupère les modos et on cacule ceux à ajouter ou à supprimer
$linkmodos=array_filter(explode(",",$form->get("linkmodos")->getData())); $linkmodos = array_filter(explode(',', $form->get('linkmodos')->getData()));
$removemodos = array_diff($oldlstmodos, $linkmodos); $removemodos = array_diff($oldlstmodos, $linkmodos);
$addmodos = array_diff($linkmodos, $oldlstmodos); $addmodos = array_diff($linkmodos, $oldlstmodos);
// Ajout des nouveaux modos // Ajout des nouveaux modos
foreach ($addmodos as $idmodo) { foreach ($addmodos as $idmodo) {
$niveau01 = $em->getRepository("App\Entity\Niveau01")->find($idmodo); $niveau01 = $em->getRepository("App\Entity\Niveau01")->find($idmodo);
$usermodo=$em->getRepository('App\Entity\UserModo')->findOneBy(["user"=>$data,"niveau01"=>$niveau01]); $usermodo = $em->getRepository('App\Entity\UserModo')->findOneBy(['user' => $data, 'niveau01' => $niveau01]);
if (!$usermodo) { if (!$usermodo) {
$usermodo = new UserModo(); $usermodo = new UserModo();
$usermodo->setUser($data); $usermodo->setUser($data);
@ -513,7 +516,7 @@ class UserController extends AbstractController
// Suppression des modos obsolètes // Suppression des modos obsolètes
foreach ($removemodos as $idmodo) { foreach ($removemodos as $idmodo) {
$niveau01 = $em->getRepository("App\Entity\Niveau01")->find($idmodo); $niveau01 = $em->getRepository("App\Entity\Niveau01")->find($idmodo);
$usermodo=$em->getRepository('App\Entity\UserModo')->findOneBy(["user"=>$data,"niveau01"=>$niveau01]); $usermodo = $em->getRepository('App\Entity\UserModo')->findOneBy(['user' => $data, 'niveau01' => $niveau01]);
if ($usermodo) { if ($usermodo) {
$em->getManager()->remove($usermodo); $em->getManager()->remove($usermodo);
$em->getManager()->flush(); $em->getManager()->flush();
@ -521,24 +524,25 @@ class UserController extends AbstractController
} }
// Retour à la liste // Retour à la liste
if($access=="user") if ('user' == $access) {
return $this->redirectToRoute("app_home"); return $this->redirectToRoute('app_home');
else } else {
return $this->redirectToRoute(str_replace("_admin_","_".$access."_",$this->route)); return $this->redirectToRoute(str_replace('_admin_', '_'.$access.'_', $this->route));
}
} }
// Affichage du formulaire // Affichage du formulaire
return $this->render($this->twig.'edit.html.twig', [ return $this->render($this->twig.'edit.html.twig', [
"useheader"=>true, 'useheader' => true,
"usemenu"=>false, 'usemenu' => false,
"usesidebar"=>($access=="admin"), 'usesidebar' => ('admin' == $access),
"access"=>$access, 'access' => $access,
"mode"=>"update", 'mode' => 'update',
"form"=>$form->createView(), 'form' => $form->createView(),
$this->data => $data, $this->data => $data,
"listgroups"=>$this->getListGroups($access,$em), 'listgroups' => $this->getListGroups($access, $em),
"listmodos"=> $this->getListModos($em), 'listmodos' => $this->getListModos($em),
"maxsize"=>($access=="user"?1200:null), 'maxsize' => ('user' == $access ? 1200 : null),
]); ]);
} }
@ -546,7 +550,9 @@ class UserController extends AbstractController
{ {
// Récupération de l'enregistrement courant // Récupération de l'enregistrement courant
$data = $em->getRepository($this->entity)->find($id); $data = $em->getRepository($this->entity)->find($id);
if (!$data) throw $this->createNotFoundException('Unable to find entity.'); if (!$data) {
throw $this->createNotFoundException('Unable to find entity.');
}
// Controler les permissions // Controler les permissions
$this->candelete($access, $data, $em); $this->candelete($access, $data, $em);
@ -555,24 +561,27 @@ class UserController extends AbstractController
try { try {
$em->getManager()->remove($data); $em->getManager()->remove($data);
$em->getManager()->flush(); $em->getManager()->flush();
} } catch (\Exception $e) {
catch (\Exception $e) { $request->getSession()->getFlashBag()->add('error', $e->getMessage());
$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).'_update', ['id' => $id]);
} }
return $this->redirectToRoute(str_replace("_admin_","_".$access."_",$this->route)); return $this->redirectToRoute(str_replace('_admin_', '_'.$access.'_', $this->route));
} }
protected function getListGroups($access, $em) protected function getListGroups($access, $em)
{ {
$qb = $em->getManager()->createQueryBuilder(); $qb = $em->getManager()->createQueryBuilder();
$qb->select('b')->from('App:Group', 'b'); $qb->select('b')->from('App:Group', 'b');
if($access!="admin") $qb->where("b.isopen=true AND b.isworkgroup=true"); if ('admin' != $access) {
$qb->andWhere("b.ldapfilter IS NULL"); $qb->where('b.isopen=true AND b.isworkgroup=true');
$qb->andWhere("b.attributes IS NULL"); }
$qb->andWhere("b.id>0"); $qb->andWhere('b.ldapfilter IS NULL');
$qb->andWhere('b.attributes IS NULL');
$qb->andWhere('b.id>0');
$datas = $qb->getQuery()->getResult(); $datas = $qb->getQuery()->getResult();
return $datas; return $datas;
} }
@ -581,47 +590,67 @@ class UserController extends AbstractController
$qb = $em->getManager()->createQueryBuilder(); $qb = $em->getManager()->createQueryBuilder();
$qb->select('b')->from('App:Niveau01', 'b'); $qb->select('b')->from('App:Niveau01', 'b');
$datas = $qb->getQuery()->getResult(); $datas = $qb->getQuery()->getResult();
return $datas; return $datas;
} }
private function cansubmit($access, $em)
private function cansubmit($access,$em) { {
switch ($access) { switch ($access) {
case "admin" : return true; break; case 'admin': return true;
case "modo" : return true; break; break;
case 'modo': return true;
break;
} }
throw $this->createAccessDeniedException('Permission denied'); throw $this->createAccessDeniedException('Permission denied');
} }
private function canupdate($access, $entity, $em)
private function canupdate($access,$entity,$em) { {
switch ($access) { switch ($access) {
case "admin" : return true; break; case 'admin': return true;
case "modo" : break;
$usermodo=$em->getRepository("App\Entity\UserModo")->findOneBy(["user"=>$this->getUser(),"niveau01"=>$entity->getNiveau01()]); case 'modo':
if(!$usermodo) throw $this->createAccessDeniedException('Permission denied'); $usermodo = $em->getRepository("App\Entity\UserModo")->findOneBy(['user' => $this->getUser(), 'niveau01' => $entity->getNiveau01()]);
if (!$usermodo) {
throw $this->createAccessDeniedException('Permission denied');
}
return true; return true;
break; break;
case "user" : case 'user':
if($this->getUser()->getId()!=$entity->getId()) throw $this->createAccessDeniedException('Permission denied'); if ($this->getUser()->getId() != $entity->getId()) {
throw $this->createAccessDeniedException('Permission denied');
}
return true; return true;
break; break;
} }
throw $this->createAccessDeniedException('Permission denied'); throw $this->createAccessDeniedException('Permission denied');
} }
private function candelete($access,$entity,$em) { private function candelete($access, $entity, $em)
{
switch ($access) { switch ($access) {
case "admin" : return true; break; case 'admin': return true;
case "modo" : break;
$usermodo=$em->getRepository("App\Entity\UserModo")->findOneBy(["user"=>$this->getUser(),"niveau01"=>$entity->getNiveau01()]); case 'modo':
if(!$usermodo) throw $this->createAccessDeniedException('Permission denied'); $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');
}
if($entity->hasRole("ROLE_ADMIN")||$entity->hasRole("ROLE_MODO")) throw $this->createAccessDeniedException('Permission denied');
return true; return true;
break; break;
case "user" : case 'user':
if($this->getUser()->getId()!=$entity->getId()) throw $this->createAccessDeniedException('Permission denied'); if ($this->getUser()->getId() != $entity->getId()) {
throw $this->createAccessDeniedException('Permission denied');
}
return true; return true;
break; break;
} }
@ -648,7 +677,7 @@ class UserController extends AbstractController
$toupdate = true; $toupdate = true;
$preference[$key] = []; $preference[$key] = [];
} }
if((!array_key_exists($id,$preference[$key]))) { if (!array_key_exists($id, $preference[$key])) {
$toupdate = true; $toupdate = true;
$preference[$key][$id] = $value; $preference[$key][$id] = $value;
} }

View File

@ -2,29 +2,28 @@
namespace App\Controller; 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\Entity\Whitelist as Entity;
use App\Form\WhitelistType as Form; use App\Form\WhitelistType as Form;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class WhitelistController extends AbstractController class WhitelistController extends AbstractController
{ {
private $data="whitelist"; private $data = 'whitelist';
private $entity = "App\Entity\Whitelist"; private $entity = "App\Entity\Whitelist";
private $twig="Whitelist/"; private $twig = 'Whitelist/';
private $route="app_admin_whitelist"; private $route = 'app_admin_whitelist';
public function list($access): Response public function list($access): Response
{ {
return $this->render($this->twig.'list.html.twig', [ return $this->render($this->twig.'list.html.twig', [
"useheader"=>true, 'useheader' => true,
"usemenu"=>false, 'usemenu' => false,
"usesidebar"=>true, 'usesidebar' => true,
"access"=>$access, 'access' => $access,
]); ]);
} }
@ -42,32 +41,32 @@ class WhitelistController extends AbstractController
$total = $em->getManager()->createQueryBuilder()->select('COUNT(entity)')->from($this->entity, 'entity')->getQuery()->getSingleScalarResult(); $total = $em->getManager()->createQueryBuilder()->select('COUNT(entity)')->from($this->entity, 'entity')->getQuery()->getSingleScalarResult();
// Nombre d'enregistrement filtré // Nombre d'enregistrement filtré
if(!$search||$search["value"]=="") if (!$search || '' == $search['value']) {
$totalf = $total; $totalf = $total;
else { } else {
$totalf = $em->getManager()->createQueryBuilder() $totalf = $em->getManager()->createQueryBuilder()
->select('COUNT(entity)') ->select('COUNT(entity)')
->from($this->entity, 'entity') ->from($this->entity, 'entity')
->where('entity.label LIKE :value') ->where('entity.label LIKE :value')
->setParameter("value", "%".$search["value"]."%") ->setParameter('value', '%'.$search['value'].'%')
->getQuery() ->getQuery()
->getSingleScalarResult(); ->getSingleScalarResult();
} }
// Construction du tableau de retour // Construction du tableau de retour
$output = array( $output = [
'draw' => $draw, 'draw' => $draw,
'recordsFiltered' => $totalf, 'recordsFiltered' => $totalf,
'recordsTotal' => $total, 'recordsTotal' => $total,
'data' => array(), 'data' => [],
); ];
// Parcours des Enregistrement // Parcours des Enregistrement
$qb = $em->getManager()->createQueryBuilder(); $qb = $em->getManager()->createQueryBuilder();
$qb->select('entity')->from($this->entity, 'entity'); $qb->select('entity')->from($this->entity, 'entity');
if($search&&$search["value"]!="") { if ($search && '' != $search['value']) {
$qb->andWhere('entity.label LIKE :value') $qb->andWhere('entity.label LIKE :value')
->setParameter("value", "%".$search["value"]."%"); ->setParameter('value', '%'.$search['value'].'%');
} }
if ($ordercolumn) { if ($ordercolumn) {
@ -82,17 +81,21 @@ class WhitelistController extends AbstractController
foreach ($datas as $data) { foreach ($datas as $data) {
// Action // Action
$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>"; $action .= "<a href='".$this->generateUrl($this->route.'_update', ['id' => $data->getId()])."'><i class='fa fa-file fa-fw fa-2x'></i></a>";
$tmp=array(); $tmp = [];
array_push($tmp, $action); array_push($tmp, $action);
array_push($tmp, $data->getLabel()); array_push($tmp, $data->getLabel());
if($this->getParameter("appMasteridentity")=="LDAP"||$this->getParameter("appSynchro")=="LDAP2NINE") array_push($tmp,$data->getLdapfilter()); if ('LDAP' == $this->getParameter('appMasteridentity') || 'LDAP2NINE' == $this->getParameter('appSynchro')) {
if($this->getParameter("appMasteridentity")=="SSO") array_push($tmp,$data->getAttributes()); array_push($tmp, $data->getLdapfilter());
}
if ('SSO' == $this->getParameter('appMasteridentity')) {
array_push($tmp, $data->getAttributes());
}
array_push($output["data"],$tmp); array_push($output['data'], $tmp);
} }
// Retour // Retour
@ -105,7 +108,7 @@ class WhitelistController extends AbstractController
$data = new Entity(); $data = new Entity();
// Création du formulaire // Création du formulaire
$form = $this->createForm(Form::class,$data,array("mode"=>"submit")); $form = $this->createForm(Form::class, $data, ['mode' => 'submit']);
// Récupération des data du formulaire // Récupération des data du formulaire
$form->handleRequest($request); $form->handleRequest($request);
@ -124,13 +127,13 @@ class WhitelistController extends AbstractController
// Affichage du formulaire // Affichage du formulaire
return $this->render($this->twig.'edit.html.twig', [ return $this->render($this->twig.'edit.html.twig', [
"useheader"=>true, 'useheader' => true,
"usemenu"=>false, 'usemenu' => false,
"usesidebar"=>true, 'usesidebar' => true,
"mode"=>"submit", 'mode' => 'submit',
"form"=>$form->createView(), 'form' => $form->createView(),
$this->data => $data, $this->data => $data,
"access"=>$access, 'access' => $access,
]); ]);
} }
@ -138,10 +141,12 @@ class WhitelistController extends AbstractController
{ {
// Initialisation de l'enregistrement // Initialisation de l'enregistrement
$data = $em->getRepository($this->entity)->find($id); $data = $em->getRepository($this->entity)->find($id);
if (!$data) throw $this->createNotFoundException('Unable to find entity.'); if (!$data) {
throw $this->createNotFoundException('Unable to find entity.');
}
// Création du formulaire // Création du formulaire
$form = $this->createForm(Form::class,$data,array("mode"=>"update")); $form = $this->createForm(Form::class, $data, ['mode' => 'update']);
// Récupération des data du formulaire // Récupération des data du formulaire
$form->handleRequest($request); $form->handleRequest($request);
@ -163,7 +168,7 @@ class WhitelistController extends AbstractController
$this->data => $data, $this->data => $data,
'mode' => 'update', 'mode' => 'update',
'form' => $form->createView(), 'form' => $form->createView(),
"access"=>$access, 'access' => $access,
]); ]);
} }
@ -171,16 +176,18 @@ class WhitelistController extends AbstractController
{ {
// Récupération de l'enregistrement courant // Récupération de l'enregistrement courant
$data = $em->getRepository($this->entity)->find($id); $data = $em->getRepository($this->entity)->find($id);
if (!$data) throw $this->createNotFoundException('Unable to find entity.'); if (!$data) {
throw $this->createNotFoundException('Unable to find entity.');
}
// Tentative de suppression // Tentative de suppression
try { try {
$em->getManager()->remove($data); $em->getManager()->remove($data);
$em->getManager()->flush(); $em->getManager()->flush();
} } catch (\Exception $e) {
catch (\Exception $e) { $request->getSession()->getFlashBag()->add('error', $e->getMessage());
$request->getSession()->getFlashBag()->add("error", $e->getMessage());
return $this->redirectToRoute($this->route."_update",["id"=>$id]); return $this->redirectToRoute($this->route.'_update', ['id' => $id]);
} }
return $this->redirectToRoute($this->route); return $this->redirectToRoute($this->route);
@ -189,14 +196,15 @@ class WhitelistController extends AbstractController
public function is(Request $request, ManagerRegistry $em) public function is(Request $request, ManagerRegistry $em)
{ {
$email = $request->request->get('email'); $email = $request->request->get('email');
$email=explode("@",$email); $email = explode('@', $email);
$domaine = end($email); $domaine = end($email);
// Rechercher le mail dans la liste blanche // Rechercher le mail dans la liste blanche
$whitelist=$em->getRepository($this->entity)->findOneBy(["label"=>$domaine]); $whitelist = $em->getRepository($this->entity)->findOneBy(['label' => $domaine]);
if($whitelist) if ($whitelist) {
return new Response("OK", 200); return new Response('OK', 200);
else } else {
return new Response("KO", 200); return new Response('KO', 200);
}
} }
} }

View File

@ -2,12 +2,10 @@
namespace App\Entity; namespace App\Entity;
use App\Repository\AuditRepository;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM; use Doctrine\ORM\Mapping as ORM;
/** /**
* Cron * Cron.
* *
* @ORM\Table(name="audit",indexes={@ORM\Index(name="search_idx", columns={"entityname", "entityid", "datesubmit"})}) * @ORM\Table(name="audit",indexes={@ORM\Index(name="search_idx", columns={"entityname", "entityid", "datesubmit"})})
* @ORM\Entity(repositoryClass="App\Repository\AuditRepository") * @ORM\Entity(repositoryClass="App\Repository\AuditRepository")
@ -35,7 +33,6 @@ class Audit
*/ */
private $datesubmit; private $datesubmit;
/** /**
* @ORM\Column(type="string", length=250, nullable=false) * @ORM\Column(type="string", length=250, nullable=false)
*/ */
@ -49,7 +46,7 @@ class Audit
/** /**
* @ORM\Column(type="array", nullable=true) * @ORM\Column(type="array", nullable=true)
*/ */
private $detail = array(); private $detail = [];
public function getId(): ?int public function getId(): ?int
{ {
@ -127,6 +124,4 @@ class Audit
return $this; return $this;
} }
} }

View File

@ -2,12 +2,10 @@
namespace App\Entity; namespace App\Entity;
use App\Repository\ConfigRepository;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM; use Doctrine\ORM\Mapping as ORM;
/** /**
* Cron * Cron.
* *
* @ORM\Table(name="config") * @ORM\Table(name="config")
* @ORM\HasLifecycleCallbacks() * @ORM\HasLifecycleCallbacks()
@ -86,8 +84,11 @@ class Config
public function getValue(): ?string public function getValue(): ?string
{ {
if($this->value=="") return $this->default; if ('' == $this->value) {
else return $this->value; return $this->default;
} else {
return $this->value;
}
} }
// == FIN DU CODE A NE PAS REGENERER // == FIN DU CODE A NE PAS REGENERER
@ -97,7 +98,6 @@ class Config
return $this->id; return $this->id;
} }
public function getTitle(): ?string public function getTitle(): ?string
{ {
return $this->title; return $this->title;

View File

@ -2,12 +2,11 @@
namespace App\Entity; namespace App\Entity;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM; use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert; use Symfony\Component\Validator\Constraints as Assert;
/** /**
* Cron * Cron.
* *
* @ORM\Table(name="cron") * @ORM\Table(name="cron")
* @ORM\Entity(repositoryClass="App\Repository\CronRepository") * @ORM\Entity(repositoryClass="App\Repository\CronRepository")
@ -15,7 +14,7 @@ use Symfony\Component\Validator\Constraints as Assert;
class Cron class Cron
{ {
/** /**
* @var integer * @var int
* *
* @ORM\Column(name="id", type="integer") * @ORM\Column(name="id", type="integer")
* @ORM\Id * @ORM\Id
@ -28,7 +27,6 @@ class Cron
* *
* @ORM\Column(name="command", type="string", nullable=false) * @ORM\Column(name="command", type="string", nullable=false)
* @Assert\NotBlank() * @Assert\NotBlank()
*
*/ */
private $command; private $command;
@ -72,11 +70,11 @@ class Cron
*/ */
private $jsonargument; private $jsonargument;
// A garder pour forcer l'id en init // A garder pour forcer l'id en init
public function setId($id) public function setId($id)
{ {
$this->id = $id; $this->id = $id;
return $this; return $this;
} }
@ -89,9 +87,12 @@ class Cron
public function getStatutLabel() public function getStatutLabel()
{ {
switch ($this->statut) { switch ($this->statut) {
case -1: return "Désactivé"; break; case -1: return 'Désactivé';
case 0: return "KO"; break; break;
case 1: return "OK"; break; case 0: return 'KO';
break;
case 1: return 'OK';
break;
} }
} }

View File

@ -1,11 +1,10 @@
<?php <?php
namespace App\Entity; 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 Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity; use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/** /**
@ -79,7 +78,7 @@ class Group
private $owner; private $owner;
/** /**
* @var ArrayCollection $users * @var ArrayCollection
* @var UserGroup * @var UserGroup
* *
* @ORM\OneToMany(targetEntity="UserGroup", mappedBy="group", cascade={"persist"}, orphanRemoval=true) * @ORM\OneToMany(targetEntity="UserGroup", mappedBy="group", cascade={"persist"}, orphanRemoval=true)
@ -95,6 +94,7 @@ class Group
public function setId(int $id): self public function setId(int $id): self
{ {
$this->id = $id; $this->id = $id;
return $this; return $this;
} }
// == FIN DU CODE A NE PAS REGENERER // == FIN DU CODE A NE PAS REGENERER

View File

@ -1,13 +1,12 @@
<?php <?php
namespace App\Entity; namespace App\Entity;
use Doctrine\Common\Collections\Collection; use App\Validator;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity; use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use App\Validator as Validator;
/** /**
* @ORM\Entity * @ORM\Entity
@ -54,7 +53,7 @@ class Niveau01
private $idexternal; private $idexternal;
/** /**
* @var ArrayCollection $niveau02s * @var ArrayCollection
* @var Registration * @var Registration
* *
* @ORM\OneToMany(targetEntity="Niveau02", mappedBy="niveau01", cascade={"persist"}, orphanRemoval=false) * @ORM\OneToMany(targetEntity="Niveau02", mappedBy="niveau01", cascade={"persist"}, orphanRemoval=false)
@ -62,7 +61,7 @@ class Niveau01
private $niveau02s; private $niveau02s;
/** /**
* @var ArrayCollection $registrations * @var ArrayCollection
* @var Registration * @var Registration
* *
* @ORM\OneToMany(targetEntity="Registration", mappedBy="niveau01", cascade={"persist"}, orphanRemoval=false) * @ORM\OneToMany(targetEntity="Registration", mappedBy="niveau01", cascade={"persist"}, orphanRemoval=false)
@ -70,16 +69,15 @@ class Niveau01
private $registrations; private $registrations;
/** /**
* @var ArrayCollection $users * @var ArrayCollection
* @var User * @var User
* *
* @ORM\OneToMany(targetEntity="User", mappedBy="niveau01", cascade={"persist"}, orphanRemoval=false) * @ORM\OneToMany(targetEntity="User", mappedBy="niveau01", cascade={"persist"}, orphanRemoval=false)
*/ */
private $users; private $users;
/** /**
* @var ArrayCollection $modos * @var ArrayCollection
* @var User * @var User
* *
* @ORM\OneToMany(targetEntity="UserModo", mappedBy="niveau01", cascade={"persist"}, orphanRemoval=false) * @ORM\OneToMany(targetEntity="UserModo", mappedBy="niveau01", cascade={"persist"}, orphanRemoval=false)
@ -94,11 +92,11 @@ class Niveau01
$this->modos = new ArrayCollection(); $this->modos = new ArrayCollection();
} }
// == CODE A NE PAS REGENERER // == CODE A NE PAS REGENERER
public function setId(int $id): self public function setId(int $id): self
{ {
$this->id = $id; $this->id = $id;
return $this; return $this;
} }
// == FIN DU CODE A NE PAS REGENERER // == FIN DU CODE A NE PAS REGENERER
@ -287,6 +285,4 @@ class Niveau01
return $this; return $this;
} }
} }

View File

@ -1,12 +1,12 @@
<?php <?php
namespace App\Entity; namespace App\Entity;
use App\Validator;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection; use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM; use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity; use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use App\Validator as Validator;
/** /**
* @ORM\Entity * @ORM\Entity
@ -44,7 +44,7 @@ class Niveau02
private $niveau01; private $niveau01;
/** /**
* @var ArrayCollection $registrations * @var ArrayCollection
* @var Registration * @var Registration
* *
* @ORM\OneToMany(targetEntity="Registration", mappedBy="niveau02", cascade={"persist"}, orphanRemoval=false) * @ORM\OneToMany(targetEntity="Registration", mappedBy="niveau02", cascade={"persist"}, orphanRemoval=false)
@ -52,7 +52,7 @@ class Niveau02
private $registrations; private $registrations;
/** /**
* @var ArrayCollection $users * @var ArrayCollection
* @var User * @var User
* *
* @ORM\OneToMany(targetEntity="User", mappedBy="niveau02", cascade={"persist"}, orphanRemoval=false) * @ORM\OneToMany(targetEntity="User", mappedBy="niveau02", cascade={"persist"}, orphanRemoval=false)
@ -165,5 +165,4 @@ class Niveau02
return $this; return $this;
} }
} }

View File

@ -1,16 +1,12 @@
<?php <?php
namespace App\Entity; namespace App\Entity;
use Doctrine\Common\Collections\Collection; use App\Validator;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM; 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 Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Security\Core\User\LegacyPasswordAuthenticatedUserInterface;
use App\Validator as Validator; use Symfony\Component\Security\Core\User\UserInterface;
/** /**
* @ORM\Entity * @ORM\Entity
@ -126,7 +122,6 @@ class Registration implements UserInterface, LegacyPasswordAuthenticatedUserInte
*/ */
private $niveau02; private $niveau02;
// == CODE A NE PAS REGENERER // == CODE A NE PAS REGENERER
private $roles; private $roles;
@ -135,7 +130,6 @@ class Registration implements UserInterface, LegacyPasswordAuthenticatedUserInte
return $this->username; return $this->username;
} }
public function setPasswordDirect($password) public function setPasswordDirect($password)
{ {
// Permet de setter le password généré lors de l'inscription // Permet de setter le password généré lors de l'inscription
@ -154,13 +148,13 @@ class Registration implements UserInterface, LegacyPasswordAuthenticatedUserInte
public function setPassword($password): self public function setPassword($password): self
{ {
if($password!=$this->password&&$password!=""){ if ($password != $this->password && '' != $password) {
// Placer le password non encodé dans une variable tempo sur laquel on va appliquer la contraite de form // Placer le password non encodé dans une variable tempo sur laquel on va appliquer la contraite de form
$this->passwordplain = $password; $this->passwordplain = $password;
// Password encrypté format openldap // Password encrypté format openldap
$this->salt = uniqid(mt_rand(), true); $this->salt = uniqid(mt_rand(), true);
$hash = "{SSHA}" . base64_encode(pack("H*", sha1($password . $this->salt)) . $this->salt); $hash = '{SSHA}'.base64_encode(pack('H*', sha1($password.$this->salt)).$this->salt);
$this->password = $hash; $this->password = $hash;
} }
@ -199,14 +193,16 @@ class Registration implements UserInterface, LegacyPasswordAuthenticatedUserInte
public function setRole(string $role): self public function setRole(string $role): self
{ {
if(!$this->hasRole($role)) if (!$this->hasRole($role)) {
array_push($this->roles, $role); array_push($this->roles, $role);
}
return $this; return $this;
} }
public function getDisplayname() { public function getDisplayname()
return $this->firstname." ".$this->lastname; {
return $this->firstname.' '.$this->lastname;
} }
// == FIN DU CODE A NE PAS REGENERER // == FIN DU CODE A NE PAS REGENERER
@ -414,5 +410,4 @@ class Registration implements UserInterface, LegacyPasswordAuthenticatedUserInte
return $this; return $this;
} }
} }

View File

@ -1,16 +1,14 @@
<?php <?php
namespace App\Entity; namespace App\Entity;
use Doctrine\Common\Collections\Collection; use App\Validator;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Symfony\Component\Security\Core\User\UserInterface; use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\LegacyPasswordAuthenticatedUserInterface;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity; use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Security\Core\User\LegacyPasswordAuthenticatedUserInterface;
use App\Validator as Validator; use Symfony\Component\Security\Core\User\UserInterface;
/** /**
* @ORM\Entity * @ORM\Entity
@ -56,7 +54,7 @@ class User implements UserInterface, LegacyPasswordAuthenticatedUserInterface
* *
* @ORM\Column(type="array", length=255) * @ORM\Column(type="array", length=255)
*/ */
private $roles = array(); private $roles = [];
/** /**
* @ORM\Column(type="string", length=250) * @ORM\Column(type="string", length=250)
@ -155,7 +153,7 @@ class User implements UserInterface, LegacyPasswordAuthenticatedUserInterface
private $niveau02; private $niveau02;
/** /**
* @var ArrayCollection $groups * @var ArrayCollection
* @var UserGroup * @var UserGroup
* *
* @ORM\OneToMany(targetEntity="UserGroup", mappedBy="user", cascade={"persist"}, orphanRemoval=true) * @ORM\OneToMany(targetEntity="UserGroup", mappedBy="user", cascade={"persist"}, orphanRemoval=true)
@ -163,7 +161,7 @@ class User implements UserInterface, LegacyPasswordAuthenticatedUserInterface
private $groups; private $groups;
/** /**
* @var ArrayCollection $ownergroups * @var ArrayCollection
* @var Group * @var Group
* *
* @ORM\OneToMany(targetEntity="Group", mappedBy="owner", cascade={"persist"}, orphanRemoval=false) * @ORM\OneToMany(targetEntity="Group", mappedBy="owner", cascade={"persist"}, orphanRemoval=false)
@ -171,7 +169,7 @@ class User implements UserInterface, LegacyPasswordAuthenticatedUserInterface
private $ownergroups; private $ownergroups;
/** /**
* @var ArrayCollection $groups * @var ArrayCollection
* @var UserGroup * @var UserGroup
* *
* @ORM\OneToMany(targetEntity="UserModo", mappedBy="user", cascade={"persist"}, orphanRemoval=true) * @ORM\OneToMany(targetEntity="UserModo", mappedBy="user", cascade={"persist"}, orphanRemoval=true)
@ -189,16 +187,15 @@ class User implements UserInterface, LegacyPasswordAuthenticatedUserInterface
public function setId(int $id): self public function setId(int $id): self
{ {
$this->id = $id; $this->id = $id;
return $this; return $this;
} }
public function getUserIdentifier(): string public function getUserIdentifier(): string
{ {
return $this->username; return $this->username;
} }
public function setPasswordDirect($password) public function setPasswordDirect($password)
{ {
// Permet de setter le password généré lors de l'inscription // Permet de setter le password généré lors de l'inscription
@ -217,13 +214,13 @@ class User implements UserInterface, LegacyPasswordAuthenticatedUserInterface
public function setPassword($password): self public function setPassword($password): self
{ {
if($password!=$this->password&&$password!=""){ if ($password != $this->password && '' != $password) {
// Placer le password non encodé dans une variable tempo sur laquel on va appliquer la contraite de form // Placer le password non encodé dans une variable tempo sur laquel on va appliquer la contraite de form
$this->passwordplain = $password; $this->passwordplain = $password;
// Password encrypté format openldap // Password encrypté format openldap
$this->salt = uniqid(mt_rand(), true); $this->salt = uniqid(mt_rand(), true);
$hash = "{SSHA}" . base64_encode(pack("H*", sha1($password . $this->salt)) . $this->salt); $hash = '{SSHA}'.base64_encode(pack('H*', sha1($password.$this->salt)).$this->salt);
$this->password = $hash; $this->password = $hash;
} }
@ -262,14 +259,16 @@ class User implements UserInterface, LegacyPasswordAuthenticatedUserInterface
public function setRole(string $role): self public function setRole(string $role): self
{ {
if(!$this->hasRole($role)) if (!$this->hasRole($role)) {
array_push($this->roles, $role); array_push($this->roles, $role);
}
return $this; return $this;
} }
public function getDisplayname() { public function getDisplayname()
return $this->firstname." ".$this->lastname; {
return $this->firstname.' '.$this->lastname;
} }
// == FIN DU CODE A NE PAS REGENERER // == FIN DU CODE A NE PAS REGENERER
@ -622,5 +621,4 @@ class User implements UserInterface, LegacyPasswordAuthenticatedUserInterface
return $this; return $this;
} }
} }

View File

@ -1,7 +1,7 @@
<?php <?php
namespace App\Entity; namespace App\Entity;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM; use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity; use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
@ -128,5 +128,4 @@ class UserGroup
return $this; return $this;
} }
} }

View File

@ -1,4 +1,5 @@
<?php <?php
namespace App\Entity; namespace App\Entity;
use Doctrine\ORM\Mapping as ORM; use Doctrine\ORM\Mapping as ORM;

View File

@ -1,8 +1,8 @@
<?php <?php
namespace App\Entity; namespace App\Entity;
use Doctrine\ORM\Mapping as ORM; use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity; use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/** /**

View File

@ -2,16 +2,14 @@
namespace App\EventListener; namespace App\EventListener;
use App\Entity\Audit;
use Doctrine\Bundle\DoctrineBundle\EventSubscriber\EventSubscriberInterface; use Doctrine\Bundle\DoctrineBundle\EventSubscriber\EventSubscriberInterface;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Event\OnFlushEventArgs;
use Doctrine\ORM\Events; use Doctrine\ORM\Events;
use Doctrine\Persistence\Event\LifecycleEventArgs; use Doctrine\Persistence\Event\LifecycleEventArgs;
use Doctrine\ORM\Event\OnFlushEventArgs;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Doctrine\ORM\Proxy\Proxy;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface; use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use App\Entity\Audit as Audit;
class AllSubscriber implements EventSubscriberInterface class AllSubscriber implements EventSubscriberInterface
{ {
@ -40,25 +38,33 @@ class AllSubscriber implements EventSubscriberInterface
$this->entity = $args->getObject(); $this->entity = $args->getObject();
// Les enregistrements négatifs sont des enregistrements systeme indispensable // Les enregistrements négatifs sont des enregistrements systeme indispensable
if($this->entity->getId()<0) if ($this->entity->getId() < 0) {
throw new \Exception("Impossible de supprimer cet enregistrement. C'est un enregistrement système"); throw new \Exception("Impossible de supprimer cet enregistrement. C'est un enregistrement système");
} }
}
public function onFlush(OnFlushEventArgs $eventArgs): void public function onFlush(OnFlushEventArgs $eventArgs): void
{ {
$this->entity = $eventArgs->getEntityManager(); $this->entity = $eventArgs->getEntityManager();
if ($this->entity instanceof Audit||!$this->params->get("auditUse")) return; if ($this->entity instanceof Audit || !$this->params->get('auditUse')) {
return;
}
$this->audit(); $this->audit();
} }
private function audit() { private function audit()
{
$token = $this->token->getToken(); $token = $this->token->getToken();
if(!$token)$user="job"; if (!$token) {
else { $user = 'job';
} else {
$user = $token->getUser(); $user = $token->getUser();
if($user!="anon.") $user = $user->getUsername(); if ('anon.' != $user) {
else $user="job"; $user = $user->getUsername();
} else {
$user = 'job';
}
} }
$uow = $this->em->getUnitOfWork(); $uow = $this->em->getUnitOfWork();
@ -66,23 +72,24 @@ class AllSubscriber implements EventSubscriberInterface
foreach ($uow->getScheduledEntityInsertions() as $entity) { foreach ($uow->getScheduledEntityInsertions() as $entity) {
$metaCar = $this->em->getClassMetadata(get_class($entity)); $metaCar = $this->em->getClassMetadata(get_class($entity));
$className=str_replace("App\\Entity\\","",$metaCar->getName()); $className = str_replace('App\\Entity\\', '', $metaCar->getName());
$nameold=""; $nameold = '';
if($metaCar->hasField("name")) if ($metaCar->hasField('name')) {
$nameold=" = ".$entity->getName(); $nameold = ' = '.$entity->getName();
elseif($metaCar->hasField("label")) } elseif ($metaCar->hasField('label')) {
$nameold=" = ".$entity->getLabel(); $nameold = ' = '.$entity->getLabel();
elseif($metaCar->hasField("username")) } elseif ($metaCar->hasField('username')) {
$nameold=" = ".$entity->getUsername(); $nameold = ' = '.$entity->getUsername();
}
$audit = new Audit(); $audit = new Audit();
$audit->setDatesubmit(new \DateTime("now")); $audit->setDatesubmit(new \DateTime('now'));
$audit->setEntityname($className); $audit->setEntityname($className);
$audit->setEntityid($entity->getId()); $audit->setEntityid($entity->getId());
$audit->setUsername($user); $audit->setUsername($user);
$audit->setDescription("SUBMIT"); $audit->setDescription('SUBMIT');
$audit->setDetail(["id"=>$entity->getId().$nameold]); $audit->setDetail(['id' => $entity->getId().$nameold]);
$this->em->persist($audit); $this->em->persist($audit);
$uow->computeChangeSet($this->em->getClassMetadata(get_class($audit)), $audit); $uow->computeChangeSet($this->em->getClassMetadata(get_class($audit)), $audit);
@ -90,23 +97,24 @@ class AllSubscriber implements EventSubscriberInterface
foreach ($uow->getScheduledEntityDeletions() as $entity) { foreach ($uow->getScheduledEntityDeletions() as $entity) {
$metaCar = $this->em->getClassMetadata(get_class($entity)); $metaCar = $this->em->getClassMetadata(get_class($entity));
$className=str_replace("App\\Entity\\","",$metaCar->getName()); $className = str_replace('App\\Entity\\', '', $metaCar->getName());
$nameold=""; $nameold = '';
if($metaCar->hasField("name")) if ($metaCar->hasField('name')) {
$nameold=" = ".$entity->getName(); $nameold = ' = '.$entity->getName();
elseif($metaCar->hasField("label")) } elseif ($metaCar->hasField('label')) {
$nameold=" = ".$entity->getLabel(); $nameold = ' = '.$entity->getLabel();
elseif($metaCar->hasField("username")) } elseif ($metaCar->hasField('username')) {
$nameold=" = ".$entity->getUsername(); $nameold = ' = '.$entity->getUsername();
}
$audit = new Audit(); $audit = new Audit();
$audit->setDatesubmit(new \DateTime("now")); $audit->setDatesubmit(new \DateTime('now'));
$audit->setEntityname($className); $audit->setEntityname($className);
$audit->setEntityid($entity->getId()); $audit->setEntityid($entity->getId());
$audit->setUsername($user); $audit->setUsername($user);
$audit->setDescription("DELETE"); $audit->setDescription('DELETE');
$audit->setDetail(["id"=>$entity->getId().$nameold]); $audit->setDetail(['id' => $entity->getId().$nameold]);
$this->em->persist($audit); $this->em->persist($audit);
$uow->computeChangeSet($this->em->getClassMetadata(get_class($audit)), $audit); $uow->computeChangeSet($this->em->getClassMetadata(get_class($audit)), $audit);
@ -116,27 +124,26 @@ class AllSubscriber implements EventSubscriberInterface
$changeSet = $uow->getEntityChangeSet($entity); $changeSet = $uow->getEntityChangeSet($entity);
// Unaudit field // Unaudit field
$className = str_replace("App\\Entity\\","",$this->em->getClassMetadata(get_class($entity))->getName()); $className = str_replace('App\\Entity\\', '', $this->em->getClassMetadata(get_class($entity))->getName());
switch ($className) { switch ($className) {
case "Audit": case 'Audit':
$changeSet = null; $changeSet = null;
break; break;
case "User": case 'User':
unset($changeSet["visitecpt"]); unset($changeSet['visitecpt']);
unset($changeSet["visitedate"]); unset($changeSet['visitedate']);
unset($changeSet["preference"]); unset($changeSet['preference']);
unset($changeSet["keyvalue"]); unset($changeSet['keyvalue']);
unset($changeSet["keyexpire"]); unset($changeSet['keyexpire']);
unset($changeSet["apikey"]); unset($changeSet['apikey']);
unset($changeSet["password"]); unset($changeSet['password']);
unset($changeSet["passwordplain"]); unset($changeSet['passwordplain']);
unset($changeSet["salt"]); unset($changeSet['salt']);
break; break;
default: default:
unset($changeSet["apikey"]); unset($changeSet['apikey']);
break; break;
} }
@ -144,48 +151,49 @@ class AllSubscriber implements EventSubscriberInterface
$mychange = []; $mychange = [];
foreach ($changeSet as $key => $value) { foreach ($changeSet as $key => $value) {
// Le champs modifié est-il une entité // Le champs modifié est-il une entité
$isentity0=($value[0]&&is_object($value[0])&&get_class($value[0])&&get_class($value[0])!="DateTime"); $isentity0 = ($value[0] && is_object($value[0]) && get_class($value[0]) && 'DateTime' != get_class($value[0]));
$isentity1=($value[1]&&is_object($value[1])&&get_class($value[1])&&get_class($value[1])!="DateTime"); $isentity1 = ($value[1] && is_object($value[1]) && get_class($value[1]) && 'DateTime' != get_class($value[1]));
if ($isentity0 || $isentity1) { if ($isentity0 || $isentity1) {
$nameold=""; $nameold = '';
if ($isentity0) { if ($isentity0) {
$metaCar = $this->em->getClassMetadata(get_class($value[0])); $metaCar = $this->em->getClassMetadata(get_class($value[0]));
if($metaCar->hasField("name")) if ($metaCar->hasField('name')) {
$nameold=" = ".$value[0]->getName(); $nameold = ' = '.$value[0]->getName();
elseif($metaCar->hasField("label")) } elseif ($metaCar->hasField('label')) {
$nameold=" = ".$value[0]->getLabel(); $nameold = ' = '.$value[0]->getLabel();
elseif($metaCar->hasField("username")) } elseif ($metaCar->hasField('username')) {
$nameold=" = ".$value[0]->getUsername(); $nameold = ' = '.$value[0]->getUsername();
}
$nameold = $value[0]->getId().$nameold; $nameold = $value[0]->getId().$nameold;
} }
$namenew = '';
$namenew="";
if ($isentity1) { if ($isentity1) {
$metaCar = $this->em->getClassMetadata(get_class($value[1])); $metaCar = $this->em->getClassMetadata(get_class($value[1]));
if($metaCar->hasField("name")) if ($metaCar->hasField('name')) {
$namenew=" = ".$value[1]->getName(); $namenew = ' = '.$value[1]->getName();
elseif($metaCar->hasField("label")) } elseif ($metaCar->hasField('label')) {
$namenew=" = ".$value[1]->getLabel(); $namenew = ' = '.$value[1]->getLabel();
elseif($metaCar->hasField("username")) } elseif ($metaCar->hasField('username')) {
$namenew=" = ".$value[1]->getUsername(); $namenew = ' = '.$value[1]->getUsername();
}
$namenew = $value[1]->getId().$namenew; $namenew = $value[1]->getId().$namenew;
} }
$mychange[$key] = [$nameold, $namenew]; $mychange[$key] = [$nameold, $namenew];
} else {
$mychange[$key] = $value;
} }
else $mychange[$key]=$value;
} }
$audit = new Audit(); $audit = new Audit();
$audit->setDatesubmit(new \DateTime("now")); $audit->setDatesubmit(new \DateTime('now'));
$audit->setEntityname($className); $audit->setEntityname($className);
$audit->setEntityid($entity->getId()); $audit->setEntityid($entity->getId());
$audit->setUsername($user); $audit->setUsername($user);
$audit->setDescription("UPDATE"); $audit->setDescription('UPDATE');
$audit->setDetail($mychange); $audit->setDetail($mychange);
$this->em->persist($audit); $this->em->persist($audit);
@ -193,6 +201,4 @@ class AllSubscriber implements EventSubscriberInterface
} }
} }
} }
} }

View File

@ -2,16 +2,15 @@
namespace App\EventListener; namespace App\EventListener;
use Doctrine\ORM\EntityManagerInterface;
use App\Entity\Group as Entity; use App\Entity\Group as Entity;
use App\Entity\UserGroup as UserGroup; use App\Entity\UserGroup;
use App\Service\LdapService;
use Doctrine\Bundle\DoctrineBundle\EventSubscriber\EventSubscriberInterface; use Doctrine\Bundle\DoctrineBundle\EventSubscriber\EventSubscriberInterface;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Events; use Doctrine\ORM\Events;
use Doctrine\Persistence\Event\LifecycleEventArgs; use Doctrine\Persistence\Event\LifecycleEventArgs;
use Ramsey\Uuid\Uuid; use Ramsey\Uuid\Uuid;
use App\Service\LdapService;
class GroupSubscriber implements EventSubscriberInterface class GroupSubscriber implements EventSubscriberInterface
{ {
private $em; private $em;
@ -24,7 +23,6 @@ class GroupSubscriber implements EventSubscriberInterface
$this->ldap = $ldap; $this->ldap = $ldap;
} }
public function getSubscribedEvents(): array public function getSubscribedEvents(): array
{ {
return [ return [
@ -39,7 +37,9 @@ class GroupSubscriber implements EventSubscriberInterface
public function postPersist(LifecycleEventArgs $args): void public function postPersist(LifecycleEventArgs $args): void
{ {
$this->entity = $args->getObject(); $this->entity = $args->getObject();
if (!$this->entity instanceof Entity) return; if (!$this->entity instanceof Entity) {
return;
}
// Synchronisation nine2ldap // Synchronisation nine2ldap
$this->nine2ldap(); $this->nine2ldap();
@ -51,13 +51,17 @@ class GroupSubscriber implements EventSubscriberInterface
public function preUpdate(LifecycleEventArgs $args): void public function preUpdate(LifecycleEventArgs $args): void
{ {
$this->entity = $args->getObject(); $this->entity = $args->getObject();
if (!$this->entity instanceof Entity) return; if (!$this->entity instanceof Entity) {
return;
}
} }
public function postUpdate(LifecycleEventArgs $args): void public function postUpdate(LifecycleEventArgs $args): void
{ {
$this->entity = $args->getObject(); $this->entity = $args->getObject();
if (!$this->entity instanceof Entity) return; if (!$this->entity instanceof Entity) {
return;
}
// Synchronisation nine2ldap // Synchronisation nine2ldap
$this->nine2ldap(); $this->nine2ldap();
@ -69,7 +73,9 @@ class GroupSubscriber implements EventSubscriberInterface
public function preRemove(LifecycleEventArgs $args): void public function preRemove(LifecycleEventArgs $args): void
{ {
$this->entity = $args->getObject(); $this->entity = $args->getObject();
if (!$this->entity instanceof Entity) return; if (!$this->entity instanceof Entity) {
return;
}
// Synchronisation nine2ldap // Synchronisation nine2ldap
$this->nine2ldapremove(); $this->nine2ldapremove();
@ -78,44 +84,47 @@ class GroupSubscriber implements EventSubscriberInterface
public function postRemove(LifecycleEventArgs $args): void public function postRemove(LifecycleEventArgs $args): void
{ {
$this->entity = $args->getObject(); $this->entity = $args->getObject();
if (!$this->entity instanceof Entity) return; if (!$this->entity instanceof Entity) {
return;
}
} }
private function nine2ldap() { private function nine2ldap()
{
if ($this->ldap->isNine2Ldap()) { if ($this->ldap->isNine2Ldap()) {
// On s'assure que la structure organisationnelle est présente // On s'assure que la structure organisationnelle est présente
$this->ldap->addOrganisations(); $this->ldap->addOrganisations();
// Ajout / Modification group dans annuaire // Ajout / Modification group dans annuaire
$filter="gidnumber=".$this->entity->getId(); $filter = 'gidnumber='.$this->entity->getId();
$attributes = $this->ldap->listAttributesGroup(); $attributes = $this->ldap->listAttributesGroup();
$ldapentrys=$this->ldap->search($filter,$attributes,$this->ldap->getParameter("basegroup")); $ldapentrys = $this->ldap->search($filter, $attributes, $this->ldap->getParameter('basegroup'));
if (empty($ldapentrys)) { if (empty($ldapentrys)) {
$this->ldap->addGroup($this->entity); $this->ldap->addGroup($this->entity);
} } elseif ($this->ldap->ismodifyGroup($this->entity, $ldapentrys[0])) {
elseif($this->ldap->ismodifyGroup($this->entity,$ldapentrys[0])) { $this->ldap->modifyGroup($this->entity, $ldapentrys[0]['cn']);
$this->ldap->modifyGroup($this->entity,$ldapentrys[0]["cn"]);
} }
} }
} }
private function nine2ldapremove()
private function nine2ldapremove() { {
if ($this->ldap->isNine2Ldap()) { if ($this->ldap->isNine2Ldap()) {
$filter="gidnumber=".$this->entity->getId(); $filter = 'gidnumber='.$this->entity->getId();
$attributes = $this->ldap->listAttributesGroup(); $attributes = $this->ldap->listAttributesGroup();
$ldapentrys=$this->ldap->search($filter,$attributes,$this->ldap->getParameter("basegroup")); $ldapentrys = $this->ldap->search($filter, $attributes, $this->ldap->getParameter('basegroup'));
if (!empty($ldapentrys)) { if (!empty($ldapentrys)) {
$this->ldap->deleteGroup($this->entity); $this->ldap->deleteGroup($this->entity);
} }
} }
} }
private function ctrlOwner() { private function ctrlOwner()
{
$group = $this->entity; $group = $this->entity;
// Le propriétaire passe manager // Le propriétaire passe manager
$usergroups=$this->em->getRepository("App\Entity\UserGroup")->findBy(["group"=>$group,"rolegroup"=>"100"]); $usergroups = $this->em->getRepository("App\Entity\UserGroup")->findBy(['group' => $group, 'rolegroup' => '100']);
foreach ($usergroups as $usergroup) { foreach ($usergroups as $usergroup) {
if ($usergroup->getUser() != $group->getOwner()) { if ($usergroup->getUser() != $group->getOwner()) {
$usergroup->setRolegroup(90); $usergroup->setRolegroup(90);
@ -125,7 +134,7 @@ class GroupSubscriber implements EventSubscriberInterface
// Le propriétaire prend son role dans le groupe // Le propriétaire prend son role dans le groupe
if ($group->getOwner()) { if ($group->getOwner()) {
$usergroup=$this->em->getRepository("App\Entity\UserGroup")->findOneBy(["group"=>$group,"user"=>$group->getOwner()]); $usergroup = $this->em->getRepository("App\Entity\UserGroup")->findOneBy(['group' => $group, 'user' => $group->getOwner()]);
if (!$usergroup) { if (!$usergroup) {
$usergroup = new UserGroup(); $usergroup = new UserGroup();
$usergroup->setUser($group->getOwner()); $usergroup->setUser($group->getOwner());
@ -134,8 +143,7 @@ class GroupSubscriber implements EventSubscriberInterface
$usergroup->setRolegroup(100); $usergroup->setRolegroup(100);
$this->em->persist($usergroup); $this->em->persist($usergroup);
$this->em->flush(); $this->em->flush();
} } elseif (100 != $usergroup->getRolegroup()) {
elseif($usergroup->getRolegroup()!=100) {
$usergroup->setRolegroup(100); $usergroup->setRolegroup(100);
$this->em->flush(); $this->em->flush();
} }

View File

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

View File

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

View File

@ -2,14 +2,13 @@
namespace App\EventListener; namespace App\EventListener;
use Doctrine\ORM\EntityManagerInterface;
use App\Entity\UserGroup as Entity; use App\Entity\UserGroup as Entity;
use App\Service\LdapService;
use Doctrine\Bundle\DoctrineBundle\EventSubscriber\EventSubscriberInterface; use Doctrine\Bundle\DoctrineBundle\EventSubscriber\EventSubscriberInterface;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Events; use Doctrine\ORM\Events;
use Doctrine\Persistence\Event\LifecycleEventArgs; use Doctrine\Persistence\Event\LifecycleEventArgs;
use App\Service\LdapService;
class UserGroupSubscriber implements EventSubscriberInterface class UserGroupSubscriber implements EventSubscriberInterface
{ {
private $em; private $em;
@ -33,8 +32,9 @@ class UserGroupSubscriber implements EventSubscriberInterface
public function postPersist(LifecycleEventArgs $args): void public function postPersist(LifecycleEventArgs $args): void
{ {
$this->entity = $args->getObject(); $this->entity = $args->getObject();
if (!$this->entity instanceof Entity) return; if (!$this->entity instanceof Entity) {
return;
}
// Synchronisation nine2ldap // Synchronisation nine2ldap
$this->nine2ldap(); $this->nine2ldap();
@ -43,13 +43,16 @@ class UserGroupSubscriber implements EventSubscriberInterface
public function preRemove(LifecycleEventArgs $args): void public function preRemove(LifecycleEventArgs $args): void
{ {
$this->entity = $args->getObject(); $this->entity = $args->getObject();
if (!$this->entity instanceof Entity) return; if (!$this->entity instanceof Entity) {
return;
}
// Synchronisation nine2ldap // Synchronisation nine2ldap
$this->nine2ldapremove(); $this->nine2ldapremove();
} }
private function nine2ldap() { private function nine2ldap()
{
if ($this->ldap->isNine2Ldap()) { if ($this->ldap->isNine2Ldap()) {
// On s'assure que la structure organisationnelle est présente // On s'assure que la structure organisationnelle est présente
$this->ldap->addOrganisations(); $this->ldap->addOrganisations();
@ -59,7 +62,8 @@ class UserGroupSubscriber implements EventSubscriberInterface
} }
} }
private function nine2ldapremove() { private function nine2ldapremove()
{
if ($this->ldap->isNine2Ldap()) { if ($this->ldap->isNine2Ldap()) {
$this->ldap->delUserGroup($this->entity); $this->ldap->delUserGroup($this->entity);
} }

View File

@ -2,16 +2,15 @@
namespace App\EventListener; namespace App\EventListener;
use Doctrine\ORM\EntityManagerInterface;
use App\Entity\User as Entity; use App\Entity\User as Entity;
use App\Entity\UserGroup as UserGroup; use App\Entity\UserGroup;
use App\Service\LdapService;
use Doctrine\Bundle\DoctrineBundle\EventSubscriber\EventSubscriberInterface; use Doctrine\Bundle\DoctrineBundle\EventSubscriber\EventSubscriberInterface;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Events; use Doctrine\ORM\Events;
use Doctrine\Persistence\Event\LifecycleEventArgs; use Doctrine\Persistence\Event\LifecycleEventArgs;
use Ramsey\Uuid\Uuid; use Ramsey\Uuid\Uuid;
use App\Service\LdapService;
class UserSubscriber implements EventSubscriberInterface class UserSubscriber implements EventSubscriberInterface
{ {
private $em; private $em;
@ -24,7 +23,6 @@ class UserSubscriber implements EventSubscriberInterface
$this->ldap = $ldap; $this->ldap = $ldap;
} }
public function getSubscribedEvents(): array public function getSubscribedEvents(): array
{ {
return [ return [
@ -39,8 +37,9 @@ class UserSubscriber implements EventSubscriberInterface
public function postPersist(LifecycleEventArgs $args): void public function postPersist(LifecycleEventArgs $args): void
{ {
$this->entity = $args->getObject(); $this->entity = $args->getObject();
if (!$this->entity instanceof Entity) return; if (!$this->entity instanceof Entity) {
return;
}
// Synchronisation nine2ldap // Synchronisation nine2ldap
$this->nine2ldap(); $this->nine2ldap();
@ -60,24 +59,32 @@ class UserSubscriber implements EventSubscriberInterface
public function preUpdate(LifecycleEventArgs $args): void public function preUpdate(LifecycleEventArgs $args): void
{ {
$this->entity = $args->getObject(); $this->entity = $args->getObject();
if (!$this->entity instanceof Entity) return; if (!$this->entity instanceof Entity) {
return;
}
} }
public function postUpdate(LifecycleEventArgs $args): void public function postUpdate(LifecycleEventArgs $args): void
{ {
$this->entity = $args->getObject(); $this->entity = $args->getObject();
if (!$this->entity instanceof Entity) return; if (!$this->entity instanceof Entity) {
return;
}
// Synchronisation nine2ldap // Synchronisation nine2ldap
$this->nine2ldap(); $this->nine2ldap();
if (!$this->entity instanceof Entity) return; if (!$this->entity instanceof Entity) {
return;
}
} }
public function preRemove(LifecycleEventArgs $args): void public function preRemove(LifecycleEventArgs $args): void
{ {
$this->entity = $args->getObject(); $this->entity = $args->getObject();
if (!$this->entity instanceof Entity) return; if (!$this->entity instanceof Entity) {
return;
}
// Synchronisation nine2ldap // Synchronisation nine2ldap
$this->nine2ldapremove(); $this->nine2ldapremove();
@ -86,23 +93,25 @@ class UserSubscriber implements EventSubscriberInterface
public function postRemove(LifecycleEventArgs $args): void public function postRemove(LifecycleEventArgs $args): void
{ {
$this->entity = $args->getObject(); $this->entity = $args->getObject();
if (!$this->entity instanceof Entity) return;; if (!$this->entity instanceof Entity) {
return;
}
} }
private function nine2ldap() { private function nine2ldap()
{
if ($this->ldap->isNine2Ldap()) { if ($this->ldap->isNine2Ldap()) {
// On s'assure que la structure organisationnelle est présente // On s'assure que la structure organisationnelle est présente
$this->ldap->addOrganisations(); $this->ldap->addOrganisations();
// Ajout / Modification dans annuaire // Ajout / Modification dans annuaire
$filter=str_replace("*",$this->entity->getUsername(),$this->ldap->getParameter("filteruser")); $filter = str_replace('*', $this->entity->getUsername(), $this->ldap->getParameter('filteruser'));
$attributes = $this->ldap->listAttributesNiveau02(); $attributes = $this->ldap->listAttributesNiveau02();
$ldapentrys=$this->ldap->search($filter,$attributes,$this->ldap->getParameter("baseuser")); $ldapentrys = $this->ldap->search($filter, $attributes, $this->ldap->getParameter('baseuser'));
if (empty($ldapentrys)) { if (empty($ldapentrys)) {
$this->ldap->addUser($this->entity); $this->ldap->addUser($this->entity);
} } elseif ($this->ldap->ismodifyUser($this->entity, $ldapentrys[0])) {
elseif($this->ldap->ismodifyUser($this->entity,$ldapentrys[0])) { $this->ldap->modifyUser($this->entity, $ldapentrys[0]['cn']);
$this->ldap->modifyUser($this->entity,$ldapentrys[0]["cn"]);
} }
// Mise à jour des niveaux du user // Mise à jour des niveaux du user
@ -110,11 +119,12 @@ class UserSubscriber implements EventSubscriberInterface
} }
} }
private function nine2ldapremove() { private function nine2ldapremove()
{
if ($this->ldap->isNine2Ldap()) { if ($this->ldap->isNine2Ldap()) {
$filter=str_replace("*",$this->entity->getUsername(),$this->ldap->getParameter("filteruser")); $filter = str_replace('*', $this->entity->getUsername(), $this->ldap->getParameter('filteruser'));
$attributes = $this->ldap->listAttributesNiveau02(); $attributes = $this->ldap->listAttributesNiveau02();
$ldapentrys=$this->ldap->search($filter,$attributes,$this->ldap->getParameter("baseuser")); $ldapentrys = $this->ldap->search($filter, $attributes, $this->ldap->getParameter('baseuser'));
if (!empty($ldapentrys)) { if (!empty($ldapentrys)) {
$this->ldap->deleteUser($this->entity); $this->ldap->deleteUser($this->entity);
} }

View File

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

View File

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

View File

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

View File

@ -1,11 +1,12 @@
<?php <?php
namespace App\Form; namespace App\Form;
use Symfony\Component\Form\AbstractType; 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; use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
class LoginType extends AbstractType class LoginType extends AbstractType
{ {
@ -13,25 +14,24 @@ class LoginType extends AbstractType
{ {
$builder->add('submit', $builder->add('submit',
SubmitType::class, [ SubmitType::class, [
"label" => "Valider", 'label' => 'Valider',
"attr" => ["class" => "btn btn-success mt-4 float-end"], 'attr' => ['class' => 'btn btn-success mt-4 float-end'],
] ]
); );
$builder->add('username', $builder->add('username',
TextType::class, [ TextType::class, [
"label" =>"Login", 'label' => 'Login',
"attr" => ["autocomplete" => "new-password"] 'attr' => ['autocomplete' => 'new-password'],
] ]
); );
$builder->add('password', $builder->add('password',
PasswordType::class, [ PasswordType::class, [
"always_empty" => true, 'always_empty' => true,
"label" => "Mot de Passe", 'label' => 'Mot de Passe',
"attr" => ["autocomplete" => "new-password"] 'attr' => ['autocomplete' => 'new-password'],
] ]
); );
} }
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -39,12 +39,11 @@ class CronRepository extends ServiceEntityRepository
// = statut = 3 (KO) 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 // = statut = 3 (KO) et nombre d'execution < nombre d'appel
$now = new \DateTime(); $now = new \DateTime();
$qb = $this->createQueryBuilder('cron') $qb = $this->createQueryBuilder('cron')
->Where('(cron.statut=0 OR cron.statut=1) AND cron.nextexecdate<:now'); ->Where('(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(); return $qb->getQuery()->setParameter('now', $now->format('Y-m-d H:i:s'))->getResult();
} }
} }

View File

@ -3,10 +3,10 @@
namespace App\Repository; namespace App\Repository;
use App\Entity\Group; use App\Entity\Group;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
use Doctrine\Common\Collections\ArrayCollection;
use App\Entity\UserGroup; use App\Entity\UserGroup;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Persistence\ManagerRegistry;
use Ramsey\Uuid\Uuid; use Ramsey\Uuid\Uuid;
class GroupRepository extends ServiceEntityRepository class GroupRepository extends ServiceEntityRepository
@ -47,22 +47,23 @@ class GroupRepository extends ServiceEntityRepository
if (array_key_exists($key, $attruser)) { if (array_key_exists($key, $attruser)) {
if (is_array($attruser[$key])) { if (is_array($attruser[$key])) {
foreach ($attruser[$key] as $val) { foreach ($attruser[$key] as $val) {
if($value=="*") if ('*' == $value) {
$retgroups->add($group); $retgroups->add($group);
elseif($val==$value) } elseif ($val == $value) {
$retgroups->add($group); $retgroups->add($group);
} }
} }
else { } else {
if($value=="*") if ('*' == $value) {
$retgroups->add($group); $retgroups->add($group);
elseif($value==$attruser[$key]) } elseif ($value == $attruser[$key]) {
$retgroups->add($group); $retgroups->add($group);
} }
} }
} }
} }
} }
}
// Pour chaque groupe de l'utilisateur // Pour chaque groupe de l'utilisateur
$usergroups = $user->getGroups(); $usergroups = $user->getGroups();
@ -70,7 +71,7 @@ class GroupRepository extends ServiceEntityRepository
// On le détache des groupes auxquelles il n'appartient plus // On le détache des groupes auxquelles il n'appartient plus
if ($usergroups) { if ($usergroups) {
foreach ($usergroups as $usergroup) { foreach ($usergroups as $usergroup) {
if($usergroup->getGroup()->getAttributes()!="") { if ('' != $usergroup->getGroup()->getAttributes()) {
if (!$retgroups->contains($usergroup->getGroup())) { if (!$retgroups->contains($usergroup->getGroup())) {
$user->removeGroup($usergroup); $user->removeGroup($usergroup);
} }
@ -80,7 +81,7 @@ class GroupRepository extends ServiceEntityRepository
// On attache le user aux groupes // On attache le user aux groupes
foreach ($retgroups as $retgroup) { foreach ($retgroups as $retgroup) {
$usergroup=$this->_em->getRepository('App\Entity\UserGroup')->findBy(["user"=>$user,"group"=>$retgroup]); $usergroup = $this->_em->getRepository('App\Entity\UserGroup')->findBy(['user' => $user, 'group' => $retgroup]);
if (!$usergroup) { if (!$usergroup) {
$usergroup = new UserGroup(); $usergroup = new UserGroup();
$usergroup->setUser($user); $usergroup->setUser($user);

View File

@ -2,12 +2,10 @@
namespace App\Repository; namespace App\Repository;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
use App\Entity\Niveau01; use App\Entity\Niveau01;
use App\Service\LdapService; use App\Service\LdapService;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
class Niveau01Repository extends ServiceEntityRepository class Niveau01Repository extends ServiceEntityRepository
{ {
@ -49,22 +47,23 @@ class Niveau01Repository extends ServiceEntityRepository
if (array_key_exists($key, $attruser)) { if (array_key_exists($key, $attruser)) {
if (is_array($attruser[$key])) { if (is_array($attruser[$key])) {
foreach ($attruser[$key] as $val) { foreach ($attruser[$key] as $val) {
if($value=="*") if ('*' == $value) {
return $niveau01; return $niveau01;
elseif($val==$value) } elseif ($val == $value) {
return $niveau01; return $niveau01;
} }
} }
else { } else {
if($value=="*") if ('*' == $value) {
return $niveau01; return $niveau01;
elseif($value==$attruser[$key]) } elseif ($value == $attruser[$key]) {
return $niveau01; return $niveau01;
} }
} }
} }
} }
} }
}
return false; return false;
} }
@ -76,7 +75,9 @@ class Niveau01Repository extends ServiceEntityRepository
foreach ($niveau01s as $niveau01) { foreach ($niveau01s as $niveau01) {
if ($niveau01->getLdapfilter()) { if ($niveau01->getLdapfilter()) {
$ismember = $this->ldapservice->findNiveau01ismember($niveau01->getLdapfilter(), $username); $ismember = $this->ldapservice->findNiveau01ismember($niveau01->getLdapfilter(), $username);
if($ismember) return $niveau01; if ($ismember) {
return $niveau01;
}
} }
} }

View File

@ -3,7 +3,6 @@
namespace App\Service; namespace App\Service;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface; use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
class ApiService class ApiService
{ {
@ -14,35 +13,42 @@ class ApiService
$this->params = $params; $this->params = $params;
} }
public function setbody(Array $array) public function setbody(array $array)
{ {
return \Unirest\Request\Body::json($array); return \Unirest\Request\Body::json($array);
} }
public function run($method,$url,$query,$header=null,$content="json") { public function run($method, $url, $query, $header = null, $content = 'json')
{
// Entete // Entete
$headerini = null; $headerini = null;
switch ($content) { switch ($content) {
case "json": case 'json':
$headerini = [ $headerini = [
'Accept' => 'application/json', 'Accept' => 'application/json',
'Content-Type' => 'application/json', 'Content-Type' => 'application/json',
]; ];
if($query) $query = \Unirest\Request\Body::json($query); if ($query) {
$query = \Unirest\Request\Body::json($query);
}
break; break;
case "form": case 'form':
$headerini = [ $headerini = [
'Accept' => 'application/json', 'Accept' => 'application/json',
'Content-Type' => 'application/x-www-form-urlencoded', 'Content-Type' => 'application/x-www-form-urlencoded',
]; ];
if($query) $query = \Unirest\Request\Body::form($query); if ($query) {
$query = \Unirest\Request\Body::form($query);
}
break; break;
} }
if($header) $header=array_merge($headerini,$header); if ($header) {
else $header=$headerini; $header = array_merge($headerini, $header);
} else {
$header = $headerini;
}
// Paramétrage unirest // Paramétrage unirest
\Unirest\Request::verifyPeer(false); \Unirest\Request::verifyPeer(false);
@ -50,60 +56,56 @@ class ApiService
\Unirest\Request::timeout(5); \Unirest\Request::timeout(5);
// Déclaration du proxy // Déclaration du proxy
$proxyUse = $this->params->get("proxyUse"); $proxyUse = $this->params->get('proxyUse');
if ($proxyUse) { if ($proxyUse) {
$proxyHost = $this->params->get("proxyHost"); $proxyHost = $this->params->get('proxyHost');
$proxyPort = $this->params->get("proxyPort"); $proxyPort = $this->params->get('proxyPort');
\Unirest\Request::proxy($proxyHost, $proxyPort, CURLPROXY_HTTP, true); \Unirest\Request::proxy($proxyHost, $proxyPort, CURLPROXY_HTTP, true);
} }
$response = false; $response = false;
switch ($method) { switch ($method) {
case "POST": case 'POST':
try { try {
$response = \Unirest\Request::post($url, $header, $query); $response = \Unirest\Request::post($url, $header, $query);
} } catch (\Exception $e) {
catch (\Exception $e) {
return false; return false;
} }
break; break;
case "GET": case 'GET':
try { try {
$response = @\Unirest\Request::get($url, $header, $query); $response = @\Unirest\Request::get($url, $header, $query);
} } catch (\Exception $e) {
catch (\Exception $e) {
return false; return false;
} }
break; break;
case "PUT": case 'PUT':
try { try {
$response = \Unirest\Request::put($url, $header, $query); $response = \Unirest\Request::put($url, $header, $query);
} } catch (\Exception $e) {
catch (\Exception $e) {
return false; return false;
} }
break; break;
case "DELETE": case 'DELETE':
try { try {
$response = \Unirest\Request::delete($url, $header, $query); $response = \Unirest\Request::delete($url, $header, $query);
} } catch (\Exception $e) {
catch (\Exception $e) {
return false; return false;
} }
break; break;
case "PATCH": case 'PATCH':
try { try {
$response = \Unirest\Request::patch($url, $header, $query); $response = \Unirest\Request::patch($url, $header, $query);
} } catch (\Exception $e) {
catch (\Exception $e) {
return false; return false;
} }
break; break;
} }
return $response; return $response;
} }
} }

View File

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

View File

@ -2,13 +2,12 @@
namespace App\Service; namespace App\Service;
use Symfony\Component\DependencyInjection\ContainerInterface; use App\Entity\Group;
use App\Entity\User;
use App\Entity\Niveau01; use App\Entity\Niveau01;
use App\Entity\Niveau02; use App\Entity\Niveau02;
use App\Entity\Group; use App\Entity\User;
use App\Entity\UserGroup; use App\Entity\UserGroup;
use Symfony\Component\DependencyInjection\ContainerInterface;
class LdapService class LdapService
{ {
@ -44,43 +43,43 @@ class LdapService
public function __construct(ContainerInterface $container) public function __construct(ContainerInterface $container)
{ {
$this->appMasteridentity = $container->getParameter('appMasteridentity');
$this->appMasteridentity = $container->getParameter("appMasteridentity"); $this->synchro = $container->getParameter('appSynchro');
$this->synchro = $container->getParameter("appSynchro"); $this->host = $container->getParameter('ldapHost');
$this->host = $container->getParameter("ldapHost"); $this->port = $container->getParameter('ldapPort');
$this->port = $container->getParameter("ldapPort"); $this->usetls = $container->getParameter('ldapUsetls');
$this->usetls = $container->getParameter("ldapUsetls"); $this->userwriter = $container->getParameter('ldapUserwriter');
$this->userwriter = $container->getParameter("ldapUserwriter"); $this->user = $container->getParameter('ldapUser');
$this->user = $container->getParameter("ldapUser"); $this->password = $container->getParameter('ldapPassword');
$this->password = $container->getParameter("ldapPassword"); $this->basedn = $container->getParameter('ldapBasedn');
$this->basedn = $container->getParameter("ldapBasedn"); $this->baseorganisation = $container->getParameter('ldapBaseorganisation');
$this->baseorganisation = $container->getParameter("ldapBaseorganisation"); $this->baseniveau01 = $container->getParameter('ldapBaseniveau01');
$this->baseniveau01 = $container->getParameter("ldapBaseniveau01"); $this->baseniveau02 = $container->getParameter('ldapBaseniveau02');
$this->baseniveau02 = $container->getParameter("ldapBaseniveau02"); $this->basegroup = $container->getParameter('ldapBasegroup');
$this->basegroup = $container->getParameter("ldapBasegroup"); $this->baseuser = $container->getParameter('ldapBaseuser');
$this->baseuser = $container->getParameter("ldapBaseuser"); $this->username = $container->getParameter('ldapUsername');
$this->username = $container->getParameter("ldapUsername"); $this->firstname = $container->getParameter('ldapFirstname');
$this->firstname = $container->getParameter("ldapFirstname"); $this->lastname = $container->getParameter('ldapLastname');
$this->lastname = $container->getParameter("ldapLastname"); $this->email = $container->getParameter('ldapEmail');
$this->email = $container->getParameter("ldapEmail"); $this->avatar = $container->getParameter('ldapAvatar');
$this->avatar = $container->getParameter("ldapAvatar"); $this->memberof = $container->getParameter('ldapMemberof');
$this->memberof = $container->getParameter("ldapMemberof"); $this->groupgid = $container->getParameter('ldapGroupgid');
$this->groupgid = $container->getParameter("ldapGroupgid"); $this->groupname = $container->getParameter('ldapGroupname');
$this->groupname = $container->getParameter("ldapGroupname"); $this->groupmember = $container->getParameter('ldapGroupmember');
$this->groupmember = $container->getParameter("ldapGroupmember"); $this->groupmemberisdn = $container->getParameter('ldapGroupmemberisdn');
$this->groupmemberisdn = $container->getParameter("ldapGroupmemberisdn"); $this->filtergroup = $container->getParameter('ldapFiltergroup');
$this->filtergroup = $container->getParameter("ldapFiltergroup"); $this->filteruser = $container->getParameter('ldapFilteruser');
$this->filteruser = $container->getParameter("ldapFilteruser");
$this->userattributes = [$this->username, $this->firstname, $this->lastname, $this->email, $this->avatar, $this->memberof]; $this->userattributes = [$this->username, $this->firstname, $this->lastname, $this->email, $this->avatar, $this->memberof];
} }
public function isNine2Ldap() { public function isNine2Ldap()
return ($this->appMasteridentity=="SQL"&&$this->synchro=="NINE2LDAP"&&$this->userwriter&&$this->baseorganisation&&$this->baseniveau01&&$this->baseniveau02&&$this->basegroup&&$this->baseuser&&$this->connect()); {
return 'SQL' == $this->appMasteridentity && 'NINE2LDAP' == $this->synchro && $this->userwriter && $this->baseorganisation && $this->baseniveau01 && $this->baseniveau02 && $this->basegroup && $this->baseuser && $this->connect();
} }
public function connect() { public function connect()
{
// Si on est déjà co = on rebind pour gérer le cas d'un timeout de connection // Si on est déjà co = on rebind pour gérer le cas d'un timeout de connection
if ($this->connection) { if ($this->connection) {
if (!@ldap_bind($this->connection, $this->user, $this->password)) { if (!@ldap_bind($this->connection, $this->user, $this->password)) {
@ -96,70 +95,91 @@ class LdapService
if ($ldapConn) { if ($ldapConn) {
ldap_set_option($ldapConn, LDAP_OPT_PROTOCOL_VERSION, 3); ldap_set_option($ldapConn, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ldapConn, LDAP_OPT_REFERRALS, 0); ldap_set_option($ldapConn, LDAP_OPT_REFERRALS, 0);
if($this->usetls) ldap_start_tls($ldapConn); if ($this->usetls) {
ldap_start_tls($ldapConn);
}
if (@ldap_bind($ldapConn, $this->user, $this->password)) { if (@ldap_bind($ldapConn, $this->user, $this->password)) {
$this->connection = $ldapConn; $this->connection = $ldapConn;
return $this->connection; return $this->connection;
} }
} }
} }
return false; return false;
} }
public function userconnect($username,$userpassword) { public function userconnect($username, $userpassword)
{
$ldapConn = ldap_connect($this->host, $this->port); $ldapConn = ldap_connect($this->host, $this->port);
$this->connection = $ldapConn; $this->connection = $ldapConn;
if ($this->connection) { if ($this->connection) {
ldap_set_option($ldapConn, LDAP_OPT_PROTOCOL_VERSION, 3); ldap_set_option($ldapConn, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ldapConn, LDAP_OPT_REFERRALS, 0); ldap_set_option($ldapConn, LDAP_OPT_REFERRALS, 0);
if($this->usetls) ldap_start_tls($ldapConn); if ($this->usetls) {
ldap_start_tls($ldapConn);
}
$dn = $this->getUserDN($username); $dn = $this->getUserDN($username);
if (@ldap_bind($ldapConn, $dn, $userpassword)) { if (@ldap_bind($ldapConn, $dn, $userpassword)) {
$res = $this->search(str_replace("*",$username,$this->filteruser),$this->userattributes, $this->baseuser); $res = $this->search(str_replace('*', $username, $this->filteruser), $this->userattributes, $this->baseuser);
$this->disconnect(); $this->disconnect();
return $res; return $res;
} }
} }
$this->disconnect(); $this->disconnect();
return false; return false;
} }
public function getParameter($key) { public function getParameter($key)
{
switch ($key) { switch ($key) {
case "baseuser" : return $this->baseuser; break; case 'baseuser': return $this->baseuser;
case "basegroup" : return $this->basegroup; break; break;
case "baseniveau01" : return $this->baseniveau01; break; case 'basegroup': return $this->basegroup;
case "baseniveau02" : return $this->baseniveau02; break; break;
case "basedn" : return $this->basedn; break; case 'baseniveau01': return $this->baseniveau01;
case "filteruser" : return $this->filteruser; break; 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 = '') { public function search($filter, $attributes = [], $subBranch = '')
{
$connection = $this->connect(); $connection = $this->connect();
$branch = ($subBranch ? $subBranch : $this->basedn); $branch = ($subBranch ? $subBranch : $this->basedn);
$result = ldap_search($connection, $branch, $filter, $attributes, 0, 0, 0); $result = ldap_search($connection, $branch, $filter, $attributes, 0, 0, 0);
if (!$result) { if (!$result) {
$this->ldapError(); $this->ldapError();
} }
return $this->resultToArray($result); return $this->resultToArray($result);
} }
public function searchdn($dn, $subBranch = '') { public function searchdn($dn, $subBranch = '')
{
$connection = $this->connect(); $connection = $this->connect();
$tbdn = ldap_explode_dn($dn, 0); $tbdn = ldap_explode_dn($dn, 0);
$branch = ($subBranch ? $subBranch : $this->basedn); $branch = ($subBranch ? $subBranch : $this->basedn);
$result = ldap_search($connection, $branch, "(".$tbdn[0].")", [],0,0,0); $result = ldap_search($connection, $branch, '('.$tbdn[0].')', [], 0, 0, 0);
if (!$result) { if (!$result) {
$this->ldapError(); $this->ldapError();
} }
return $this->resultToArray($result); return $this->resultToArray($result);
} }
public function deleteByDN($dn){ public function deleteByDN($dn)
{
$connection = $this->connect(); $connection = $this->connect();
$removed = ldap_delete($connection, $dn); $removed = ldap_delete($connection, $dn);
if (!$removed) { if (!$removed) {
@ -167,34 +187,37 @@ class LdapService
} }
} }
public function rename($oldDN, $newDN, $parentDN = '', $deleteOldDN = true){ public function rename($oldDN, $newDN, $parentDN = '', $deleteOldDN = true)
{
$connection = $this->connect(); $connection = $this->connect();
$result = ldap_rename($connection, $oldDN, $newDN, $parentDN, $deleteOldDN); $result = ldap_rename($connection, $oldDN, $newDN, $parentDN, $deleteOldDN);
if(!$result) $this->ldapError(); if (!$result) {
$this->ldapError();
}
return $result; return $result;
} }
private function resultToArray($result)
private function resultToArray($result){ {
$connection = $this->connect(); $connection = $this->connect();
$resultArray = array(); $resultArray = [];
if ($result) { if ($result) {
$entry = ldap_first_entry($connection, $result); $entry = ldap_first_entry($connection, $result);
while ($entry) { while ($entry) {
$row = array(); $row = [];
$attr = ldap_first_attribute($connection, $entry); $attr = ldap_first_attribute($connection, $entry);
while ($attr) { while ($attr) {
$val = ldap_get_values_len($connection, $entry, $attr); $val = ldap_get_values_len($connection, $entry, $attr);
if(array_key_exists('count', $val) AND $val['count'] == 1){ if (array_key_exists('count', $val) and 1 == $val['count']) {
$row[strtolower($attr)] = $val[0]; $row[strtolower($attr)] = $val[0];
} else { } else {
$row[strtolower($attr)] = $val; $row[strtolower($attr)] = $val;
} }
if (is_array($row[strtolower($attr)])) { if (is_array($row[strtolower($attr)])) {
unset($row[strtolower($attr)]["count"]); unset($row[strtolower($attr)]['count']);
} }
$attr = ldap_next_attribute($connection, $entry); $attr = ldap_next_attribute($connection, $entry);
@ -207,35 +230,40 @@ class LdapService
return $resultArray; return $resultArray;
} }
public function in_array_r($item , $array){ public function in_array_r($item, $array)
{
return preg_match('/"'.$item.'"/i', json_encode($array)); return preg_match('/"'.$item.'"/i', json_encode($array));
} }
public function disconnect(){ public function disconnect()
{
if ($this->connection) { if ($this->connection) {
ldap_unbind($this->connection); ldap_unbind($this->connection);
$this->connection = null; $this->connection = null;
} }
} }
public function ldapError(){ public function ldapError()
{
$connection = $this->connect(); $connection = $this->connect();
throw new \Exception( throw new \Exception('Error: ('.ldap_errno($connection).') '.ldap_error($connection));
'Error: ('. ldap_errno($connection) .') '. ldap_error($connection)
);
} }
public function ldapModify($dn,$attrs) { public function ldapModify($dn, $attrs)
{
$connection = $this->connect(); $connection = $this->connect();
$result = ldap_modify($connection, $dn, $attrs); $result = ldap_modify($connection, $dn, $attrs);
if(!$result) $this->ldapError(); if (!$result) {
$this->ldapError();
}
} }
// ================================================================================================================================================================== // ==================================================================================================================================================================
// == Function Organisation========================================================================================================================================== // == Function Organisation==========================================================================================================================================
// ================================================================================================================================================================== // ==================================================================================================================================================================
public function addOrganisations() { public function addOrganisations()
{
$ldapentrys = $this->searchdn($this->baseorganisation); $ldapentrys = $this->searchdn($this->baseorganisation);
if (empty($ldapentrys)) { if (empty($ldapentrys)) {
$this->addOrganisation($this->baseorganisation); $this->addOrganisation($this->baseorganisation);
@ -262,13 +290,15 @@ class LdapService
} }
} }
public function addOrganisation($dn) { public function addOrganisation($dn)
{
$connection = $this->connect(); $connection = $this->connect();
$attrs = array(); $attrs = [];
$attrs['objectclass'] = ["top","organizationalUnit"]; $attrs['objectclass'] = ['top', 'organizationalUnit'];
$result = ldap_add($connection, $dn, $attrs); $result = ldap_add($connection, $dn, $attrs);
if(!$result) $this->ldapError(); if (!$result) {
$this->ldapError();
}
return $result; return $result;
} }
@ -277,12 +307,12 @@ class LdapService
// == Function User================================================================================================================================================== // == Function User==================================================================================================================================================
// ================================================================================================================================================================== // ==================================================================================================================================================================
public function addUser(User $user) { public function addUser(User $user)
{
$connection = $this->connect(); $connection = $this->connect();
$dn = $this->getUserDN($user->getUsername()); $dn = $this->getUserDN($user->getUsername());
$attrs = array(); $attrs = [];
$attrs['objectclass'] = $this->getObjectClassesUser(); $attrs['objectclass'] = $this->getObjectClassesUser();
$this->fillAttributesUser($user, $attrs); $this->fillAttributesUser($user, $attrs);
@ -292,35 +322,44 @@ class LdapService
} }
} }
$result = ldap_add($connection, $dn, $attrs); $result = ldap_add($connection, $dn, $attrs);
if(!$result) $this->ldapError(); if (!$result) {
$this->ldapError();
}
return $result; return $result;
} }
public function ismodifyUser(User $user,$entry){ public function ismodifyUser(User $user, $entry)
{
$attrs = []; $attrs = [];
$this->fillAttributesUser($user, $attrs); $this->fillAttributesUser($user, $attrs);
foreach ($attrs as $key => $value) { foreach ($attrs as $key => $value) {
if(!array_key_exists($key,$entry)&&!empty($value)) return true; if (!array_key_exists($key, $entry) && !empty($value)) {
elseif(array_key_exists($key,$entry)&&$value!=$entry[$key]) return true; return true;
} elseif (array_key_exists($key, $entry) && $value != $entry[$key]) {
return true;
}
} }
foreach ($entry as $key => $value) { foreach ($entry as $key => $value) {
if(!array_key_exists($key,$attrs)&&!empty($value)) return true; if (!array_key_exists($key, $attrs) && !empty($value)) {
elseif(array_key_exists($key,$attrs)&&$value!=$attrs[$key]) return true; return true;
} elseif (array_key_exists($key, $attrs) && $value != $attrs[$key]) {
return true;
}
} }
return false; return false;
} }
public function modifyUser(User $user){ public function modifyUser(User $user)
{
$dn = $this->basedn; $dn = $this->basedn;
$connection = $this->connect(); $connection = $this->connect();
$attrs = array(); $attrs = [];
$this->fillAttributesUser($user, $attrs); $this->fillAttributesUser($user, $attrs);
// Rechercher le DN du user // Rechercher le DN du user
@ -329,21 +368,23 @@ class LdapService
foreach ($attrs as $key => $value) { foreach ($attrs as $key => $value) {
if (empty($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 // 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())); @ldap_mod_del($connection, $dn, [$key => []]);
unset($attrs[$key]); unset($attrs[$key]);
} }
} }
$result = ldap_modify($connection, $dn, $attrs); $result = ldap_modify($connection, $dn, $attrs);
if(!$result) $this->ldapError(); if (!$result) {
$this->ldapError();
}
} }
public function modifyUserpwd(User $user)
public function modifyUserpwd(User $user){ {
$dn = $this->basedn; $dn = $this->basedn;
$connection = $this->connect(); $connection = $this->connect();
$attrs = array(); $attrs = [];
// Attributs associés au password // Attributs associés au password
$attrs['userpassword'] = $user->getPassword(); $attrs['userpassword'] = $user->getPassword();
@ -354,17 +395,19 @@ class LdapService
foreach ($attrs as $key => $value) { foreach ($attrs as $key => $value) {
if (empty($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 // 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())); @ldap_mod_del($connection, $dn, [$key => []]);
unset($attrs[$key]); unset($attrs[$key]);
} }
} }
$result = ldap_modify($connection, $dn, $attrs); $result = ldap_modify($connection, $dn, $attrs);
if(!$result) $this->ldapError(); if (!$result) {
$this->ldapError();
}
} }
public function updateNiveauUser(User $user,$todel=false) { public function updateNiveauUser(User $user, $todel = false)
{
$dn = $this->basedn; $dn = $this->basedn;
$connection = $this->connect(); $connection = $this->connect();
$result = null; $result = null;
@ -373,14 +416,16 @@ class LdapService
// On recherche le Niveau01 actuellement asscocié à l'utilisateur // On recherche le Niveau01 actuellement asscocié à l'utilisateur
$criteria = '(&(cn=*)(memberUid='.$user->getUsername().'))'; $criteria = '(&(cn=*)(memberUid='.$user->getUsername().'))';
$subbranch = $this->baseniveau01; $subbranch = $this->baseniveau01;
$results = $this->search($criteria, array('cn'), $subbranch); $results = $this->search($criteria, ['cn'], $subbranch);
foreach ($results as $result) { foreach ($results as $result) {
// Si Niveau01 différent de celui en cours on le détache de ce Niveau01 // Si Niveau01 différent de celui en cours on le détache de ce Niveau01
if($result["cn"]!=$user->getNiveau01()->getLabel()||$todel) { if ($result['cn'] != $user->getNiveau01()->getLabel() || $todel) {
$dn = $this->getNiveau01DN($result["cn"]); $dn = $this->getNiveau01DN($result['cn']);
$entry['memberuid'] = $user->getUsername(); $entry['memberuid'] = $user->getUsername();
$result = ldap_mod_del($connection, $dn, $entry); $result = ldap_mod_del($connection, $dn, $entry);
if(!$result) $this->ldapError(); if (!$result) {
$this->ldapError();
}
} }
} }
@ -388,14 +433,16 @@ class LdapService
if (!$todel) { if (!$todel) {
$criteria = '(cn='.$user->getNiveau01()->getLabel().')'; $criteria = '(cn='.$user->getNiveau01()->getLabel().')';
$subbranch = $this->baseniveau01; $subbranch = $this->baseniveau01;
$result = $this->search($criteria, array('memberuid'), $subbranch); $result = $this->search($criteria, ['memberuid'], $subbranch);
// S'il n'est pas membre du Niveau01 on le rattache // S'il n'est pas membre du Niveau01 on le rattache
if (!$this->in_array_r($user->getUsername(), $result[0])) { if (!$this->in_array_r($user->getUsername(), $result[0])) {
$dn = $this->getNiveau01DN($user->getNiveau01()->getLabel()); $dn = $this->getNiveau01DN($user->getNiveau01()->getLabel());
$entry['memberuid'] = $user->getUsername(); $entry['memberuid'] = $user->getUsername();
$result = ldap_mod_add($connection, $dn, $entry); $result = ldap_mod_add($connection, $dn, $entry);
if(!$result) $this->ldapError(); if (!$result) {
$this->ldapError();
}
} }
} }
@ -403,30 +450,34 @@ class LdapService
// On recherche le Niveau02 actuellement asscocié à l'utilisateur // On recherche le Niveau02 actuellement asscocié à l'utilisateur
$criteria = '(&(cn=*)(memberUid='.$user->getUsername().'))'; $criteria = '(&(cn=*)(memberUid='.$user->getUsername().'))';
$subbranch = $this->baseniveau02; $subbranch = $this->baseniveau02;
$results = $this->search($criteria, array('cn'), $subbranch); $results = $this->search($criteria, ['cn'], $subbranch);
foreach ($results as $result) { foreach ($results as $result) {
// Si Niveau02 différent de celui en cours on le détache de ce Niveau02 // 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) { if (null === $user->getNiveau02() || $result['cn'] != $user->getNiveau02()->getLabel() || $todel) {
$dn = $this->getNiveau02DN($result["cn"]); $dn = $this->getNiveau02DN($result['cn']);
$entry['memberuid'] = $user->getUsername(); $entry['memberuid'] = $user->getUsername();
$result = ldap_mod_del($connection, $dn, $entry); $result = ldap_mod_del($connection, $dn, $entry);
if(!$result) $this->ldapError(); if (!$result) {
$this->ldapError();
}
} }
} }
// On recherche le Niveau02 en cours // On recherche le Niveau02 en cours
if (!$todel) { if (!$todel) {
if($user->getNiveau02()!==null) { if (null !== $user->getNiveau02()) {
$criteria = '(cn='.$user->getNiveau02()->getLabel().')'; $criteria = '(cn='.$user->getNiveau02()->getLabel().')';
$subbranch = $this->baseniveau02; $subbranch = $this->baseniveau02;
$result = $this->search($criteria, array('memberuid'), $subbranch); $result = $this->search($criteria, ['memberuid'], $subbranch);
// S'il n'est pas membre du Niveau02 on le rattache // S'il n'est pas membre du Niveau02 on le rattache
if (empty($result) || !$this->in_array_r($user->getUsername(), $result[0])) { if (empty($result) || !$this->in_array_r($user->getUsername(), $result[0])) {
$dn = $this->getNiveau02DN($user->getNiveau02()->getLabel()); $dn = $this->getNiveau02DN($user->getNiveau02()->getLabel());
$entry['memberuid'] = $user->getUsername(); $entry['memberuid'] = $user->getUsername();
$result = ldap_mod_add($connection, $dn, $entry); $result = ldap_mod_add($connection, $dn, $entry);
if(!$result) $this->ldapError(); if (!$result) {
$this->ldapError();
}
} }
} }
} }
@ -434,36 +485,42 @@ class LdapService
return $result; return $result;
} }
public function deleteUser(User $user){ public function deleteUser(User $user)
{
$dn = $this->getUserDN($user->getUsername()); $dn = $this->getUserDN($user->getUsername());
return $this->deleteByDN($dn); return $this->deleteByDN($dn);
} }
public function getObjectClassesUser() { public function getObjectClassesUser()
$oc = array( {
$oc = [
'top', 'top',
'person', 'person',
'organizationalPerson', 'organizationalPerson',
'inetOrgPerson', 'inetOrgPerson',
); ];
return $oc; return $oc;
} }
public function listAttributesUser() { public function listAttributesUser()
{
return [ return [
"uid", 'uid',
"cn", 'cn',
"givenname", 'givenname',
"sn", 'sn',
"mail", 'mail',
"displayname", 'displayname',
"telephonenumber", 'telephonenumber',
"postaladdress", 'postaladdress',
"userpassword", 'userpassword',
]; ];
} }
public function fillAttributesUser(User $user, array &$attrs) { public function fillAttributesUser(User $user, array &$attrs)
{
$attrs['uid'] = $user->getUsername(); $attrs['uid'] = $user->getUsername();
$attrs['cn'] = $user->getFirstname().' '.$user->getLastname(); $attrs['cn'] = $user->getFirstname().' '.$user->getLastname();
$attrs['givenname'] = $user->getFirstname(); $attrs['givenname'] = $user->getFirstname();
@ -475,7 +532,8 @@ class LdapService
$attrs['userpassword'] = $user->getPassword(); $attrs['userpassword'] = $user->getPassword();
} }
public function getUserDN($username) { public function getUserDN($username)
{
return $this->username.'='.$username.','.$this->baseuser; return $this->username.'='.$username.','.$this->baseuser;
} }
@ -483,28 +541,35 @@ class LdapService
// == Function Niveau01============================================================================================================================================== // == Function Niveau01==============================================================================================================================================
// ================================================================================================================================================================== // ==================================================================================================================================================================
public function findNiveau01($ldapfilter) { public function findNiveau01($ldapfilter)
{
$ldapentrys = $this->search($ldapfilter, [$this->groupgid, $this->groupname, $this->groupmember], $this->baseniveau01); $ldapentrys = $this->search($ldapfilter, [$this->groupgid, $this->groupname, $this->groupmember], $this->baseniveau01);
return $ldapentrys; return $ldapentrys;
} }
public function findNiveau01ismember($ldapfilter,$username) { public function findNiveau01ismember($ldapfilter, $username)
{
$ldapentrys = $this->findNiveau01($ldapfilter); $ldapentrys = $this->findNiveau01($ldapfilter);
foreach ($ldapentrys as $ldapentry) { foreach ($ldapentrys as $ldapentry) {
if (is_array($ldapentry[$this->groupmember])) { if (is_array($ldapentry[$this->groupmember])) {
if(in_array($username,$ldapentry[$this->groupmember])) return true; if (in_array($username, $ldapentry[$this->groupmember])) {
return true;
} }
elseif($username==$ldapentry[$this->groupmember]) return true; } elseif ($username == $ldapentry[$this->groupmember]) {
return true;
} }
}
return false; return false;
} }
public function addNiveau01(Niveau01 $niveau01) { public function addNiveau01(Niveau01 $niveau01)
{
$connection = $this->connect(); $connection = $this->connect();
$dn = $this->getNiveau01DN($niveau01->getLabel()); $dn = $this->getNiveau01DN($niveau01->getLabel());
$attrs = array(); $attrs = [];
$attrs['objectclass'] = $this->getObjectClassesNiveau01(); $attrs['objectclass'] = $this->getObjectClassesNiveau01();
$this->fillAttributesNiveau01($niveau01, $attrs); $this->fillAttributesNiveau01($niveau01, $attrs);
@ -515,80 +580,95 @@ class LdapService
} }
$result = ldap_add($connection, $dn, $attrs); $result = ldap_add($connection, $dn, $attrs);
if(!$result) $this->ldapError(); if (!$result) {
$this->ldapError();
}
return $result; return $result;
} }
public function ismodifyNiveau01(Niveau01 $niveau01, $entry)
public function ismodifyNiveau01(Niveau01 $niveau01,$entry){ {
$attrs = []; $attrs = [];
$this->fillAttributesNiveau01($niveau01, $attrs); $this->fillAttributesNiveau01($niveau01, $attrs);
foreach ($attrs as $key => $value) { foreach ($attrs as $key => $value) {
if(!array_key_exists($key,$entry)&&!empty($value)) return true; if (!array_key_exists($key, $entry) && !empty($value)) {
elseif(array_key_exists($key,$entry)&&$value!=$entry[$key]) return true; return true;
} elseif (array_key_exists($key, $entry) && $value != $entry[$key]) {
return true;
}
} }
foreach ($entry as $key => $value) { foreach ($entry as $key => $value) {
if(!array_key_exists($key,$attrs)&&!empty($value)) return true; if (!array_key_exists($key, $attrs) && !empty($value)) {
elseif(array_key_exists($key,$attrs)&&$value!=$attrs[$key]) return true; return true;
} elseif (array_key_exists($key, $attrs) && $value != $attrs[$key]) {
return true;
}
} }
return false; return false;
} }
public function modifyNiveau01(Niveau01 $niveau01,$oldid){ public function modifyNiveau01(Niveau01 $niveau01, $oldid)
{
$dn = $this->basedn; $dn = $this->basedn;
$connection = $this->connect(); $connection = $this->connect();
$attrs = array(); $attrs = [];
$this->fillAttributesNiveau01($niveau01, $attrs); $this->fillAttributesNiveau01($niveau01, $attrs);
unset($attrs["cn"]); unset($attrs['cn']);
$dn = $this->getNiveau01DN($niveau01->getLabel()); $dn = $this->getNiveau01DN($niveau01->getLabel());
foreach ($attrs as $key => $value) { foreach ($attrs as $key => $value) {
if (empty($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 // 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())); @ldap_mod_del($connection, $dn, [$key => []]);
unset($attrs[$key]); unset($attrs[$key]);
} }
} }
if (isset($oldid) && $oldid != $niveau01->getLabel()) { if (isset($oldid) && $oldid != $niveau01->getLabel()) {
$olddn = $this->getNiveau01DN($oldid); $olddn = $this->getNiveau01DN($oldid);
$this->rename($olddn,"cn=".$niveau01->getLabel(),$this->baseniveau01); $this->rename($olddn, 'cn='.$niveau01->getLabel(), $this->baseniveau01);
} }
$result = ldap_modify($connection, $dn, $attrs); $result = ldap_modify($connection, $dn, $attrs);
if(!$result) $this->ldapError(); if (!$result) {
$this->ldapError();
}
} }
public function deleteNiveau01(Niveau01 $niveau01){ public function deleteNiveau01(Niveau01 $niveau01)
{
$dn = $this->getNiveau01DN($niveau01->getLabel()); $dn = $this->getNiveau01DN($niveau01->getLabel());
return $this->deleteByDN($dn); return $this->deleteByDN($dn);
} }
private function getObjectClassesNiveau01() { private function getObjectClassesNiveau01()
$oc = array( {
$oc = [
'top', 'top',
'posixGroup', 'posixGroup',
); ];
return $oc; return $oc;
} }
public function listAttributesNiveau01() { public function listAttributesNiveau01()
{
return [ return [
"cn", 'cn',
"gidnumber", 'gidnumber',
"memberuid", 'memberuid',
]; ];
} }
public function fillAttributesNiveau01(Niveau01 $niveau01, array &$attrs) { public function fillAttributesNiveau01(Niveau01 $niveau01, array &$attrs)
{
$attrs['cn'] = $niveau01->getLabel(); $attrs['cn'] = $niveau01->getLabel();
$attrs['gidnumber'] = $niveau01->getId(); $attrs['gidnumber'] = $niveau01->getId();
@ -598,10 +678,13 @@ class LdapService
} }
sort($attrs['memberuid']); sort($attrs['memberuid']);
if(count($attrs['memberuid'])==1) $attrs['memberuid'] = $attrs['memberuid'][0]; if (1 == count($attrs['memberuid'])) {
$attrs['memberuid'] = $attrs['memberuid'][0];
}
} }
public function getNiveau01DN($id) { public function getNiveau01DN($id)
{
return 'cn='.$id.','.$this->baseniveau01; return 'cn='.$id.','.$this->baseniveau01;
} }
@ -609,12 +692,12 @@ class LdapService
// == Function Niveau02============================================================================================================================================== // == Function Niveau02==============================================================================================================================================
// ================================================================================================================================================================== // ==================================================================================================================================================================
public function addNiveau02(Niveau02 $niveau02) { public function addNiveau02(Niveau02 $niveau02)
{
$connection = $this->connect(); $connection = $this->connect();
$dn = $this->getNiveau02DN($niveau02->getLabel()); $dn = $this->getNiveau02DN($niveau02->getLabel());
$attrs = array(); $attrs = [];
$attrs['objectclass'] = $this->getObjectClassesNiveau02(); $attrs['objectclass'] = $this->getObjectClassesNiveau02();
$this->fillAttributesNiveau02($niveau02, $attrs); $this->fillAttributesNiveau02($niveau02, $attrs);
@ -625,80 +708,95 @@ class LdapService
} }
$result = ldap_add($connection, $dn, $attrs); $result = ldap_add($connection, $dn, $attrs);
if(!$result) $this->ldapError(); if (!$result) {
$this->ldapError();
}
return $result; return $result;
} }
public function ismodifyNiveau02(Niveau02 $niveau02,$entry){ public function ismodifyNiveau02(Niveau02 $niveau02, $entry)
{
$attrs = []; $attrs = [];
$this->fillAttributesNiveau02($niveau02, $attrs); $this->fillAttributesNiveau02($niveau02, $attrs);
foreach ($attrs as $key => $value) { foreach ($attrs as $key => $value) {
if(!array_key_exists($key,$entry)&&!empty($value)) return true; if (!array_key_exists($key, $entry) && !empty($value)) {
elseif(array_key_exists($key,$entry)&&$value!=$entry[$key]) return true; return true;
} elseif (array_key_exists($key, $entry) && $value != $entry[$key]) {
return true;
}
} }
foreach ($entry as $key => $value) { foreach ($entry as $key => $value) {
if(!array_key_exists($key,$attrs)&&!empty($value)) return true; if (!array_key_exists($key, $attrs) && !empty($value)) {
elseif(array_key_exists($key,$attrs)&&$value!=$attrs[$key]) return true; return true;
} elseif (array_key_exists($key, $attrs) && $value != $attrs[$key]) {
return true;
}
} }
return false; return false;
} }
public function modifyNiveau02(Niveau02 $niveau02,$oldid){ public function modifyNiveau02(Niveau02 $niveau02, $oldid)
{
$dn = $this->basedn; $dn = $this->basedn;
$connection = $this->connect(); $connection = $this->connect();
$attrs = array(); $attrs = [];
$this->fillAttributesNiveau02($niveau02, $attrs); $this->fillAttributesNiveau02($niveau02, $attrs);
unset($attrs["cn"]); unset($attrs['cn']);
$dn = $this->getNiveau02DN($niveau02->getLabel()); $dn = $this->getNiveau02DN($niveau02->getLabel());
foreach ($attrs as $key => $value) { foreach ($attrs as $key => $value) {
if (empty($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 // 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())); @ldap_mod_del($connection, $dn, [$key => []]);
unset($attrs[$key]); unset($attrs[$key]);
} }
} }
if (isset($oldid) && $oldid != $niveau02->getLabel()) { if (isset($oldid) && $oldid != $niveau02->getLabel()) {
$olddn = $this->getNiveau02DN($oldid); $olddn = $this->getNiveau02DN($oldid);
$this->rename($olddn,"cn=".$niveau02->getLabel(),$this->baseniveau02); $this->rename($olddn, 'cn='.$niveau02->getLabel(), $this->baseniveau02);
} }
$result = ldap_modify($connection, $dn, $attrs); $result = ldap_modify($connection, $dn, $attrs);
if(!$result) $this->ldapError(); if (!$result) {
$this->ldapError();
}
} }
public function deleteNiveau02(Niveau02 $niveau02)
{
public function deleteNiveau02(Niveau02 $niveau02){
$dn = $this->getNiveau02DN($niveau02->getLabel()); $dn = $this->getNiveau02DN($niveau02->getLabel());
return $this->deleteByDN($dn); return $this->deleteByDN($dn);
} }
private function getObjectClassesNiveau02() { private function getObjectClassesNiveau02()
$oc = array( {
$oc = [
'top', 'top',
'posixGroup', 'posixGroup',
); ];
return $oc; return $oc;
} }
public function listAttributesNiveau02() { public function listAttributesNiveau02()
{
return [ return [
"cn", 'cn',
"gidnumber", 'gidnumber',
"memberuid" 'memberuid',
]; ];
} }
public function fillAttributesNiveau02(Niveau02 $niveau02, array &$attrs) { public function fillAttributesNiveau02(Niveau02 $niveau02, array &$attrs)
{
$attrs['cn'] = $niveau02->getLabel(); $attrs['cn'] = $niveau02->getLabel();
$attrs['gidnumber'] = $niveau02->getId(); $attrs['gidnumber'] = $niveau02->getId();
@ -708,11 +806,13 @@ class LdapService
} }
sort($attrs['memberuid']); sort($attrs['memberuid']);
if(count($attrs['memberuid'])==1) $attrs['memberuid'] = $attrs['memberuid'][0]; if (1 == count($attrs['memberuid'])) {
$attrs['memberuid'] = $attrs['memberuid'][0];
}
} }
public function getNiveau02DN($id) { public function getNiveau02DN($id)
{
return 'cn='.$id.','.$this->baseniveau02; return 'cn='.$id.','.$this->baseniveau02;
} }
@ -720,12 +820,12 @@ class LdapService
// == Function Group================================================================================================================================================= // == Function Group=================================================================================================================================================
// ================================================================================================================================================================== // ==================================================================================================================================================================
public function addGroup(Group $group) { public function addGroup(Group $group)
{
$connection = $this->connect(); $connection = $this->connect();
$dn = $this->getGroupDN($group->getLabel()); $dn = $this->getGroupDN($group->getLabel());
$attrs = array(); $attrs = [];
$attrs['objectclass'] = $this->getObjectClassesGroup(); $attrs['objectclass'] = $this->getObjectClassesGroup();
$this->fillAttributesGroup($group, $attrs); $this->fillAttributesGroup($group, $attrs);
@ -736,91 +836,111 @@ class LdapService
} }
$result = ldap_add($connection, $dn, $attrs); $result = ldap_add($connection, $dn, $attrs);
if(!$result) $this->ldapError(); if (!$result) {
$this->ldapError();
}
return $result; return $result;
} }
public function ismodifyGroup(Group $group,$entry){ public function ismodifyGroup(Group $group, $entry)
{
$attrs = []; $attrs = [];
$this->fillAttributesGroup($group, $attrs); $this->fillAttributesGroup($group, $attrs);
foreach ($attrs as $key => $value) { foreach ($attrs as $key => $value) {
if(!array_key_exists($key,$entry)&&!empty($value)) return true; if (!array_key_exists($key, $entry) && !empty($value)) {
elseif(array_key_exists($key,$entry)&&$value!=$entry[$key]) return true; return true;
} elseif (array_key_exists($key, $entry) && $value != $entry[$key]) {
return true;
}
} }
foreach ($entry as $key => $value) { foreach ($entry as $key => $value) {
if(!array_key_exists($key,$attrs)&&!empty($value)) return true; if (!array_key_exists($key, $attrs) && !empty($value)) {
elseif(array_key_exists($key,$attrs)&&$value!=$attrs[$key]) return true; return true;
} elseif (array_key_exists($key, $attrs) && $value != $attrs[$key]) {
return true;
}
} }
return false; return false;
} }
public function modifyGroup(Group $group,$oldid){ public function modifyGroup(Group $group, $oldid)
{
$dn = $this->basedn; $dn = $this->basedn;
$connection = $this->connect(); $connection = $this->connect();
$attrs = array(); $attrs = [];
$this->fillAttributesGroup($group, $attrs); $this->fillAttributesGroup($group, $attrs);
unset($attrs["cn"]); unset($attrs['cn']);
$dn = $this->getGroupDN($group->getLabel()); $dn = $this->getGroupDN($group->getLabel());
foreach ($attrs as $key => $value) { foreach ($attrs as $key => $value) {
if (empty($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 // 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())); @ldap_mod_del($connection, $dn, [$key => []]);
unset($attrs[$key]); unset($attrs[$key]);
} }
} }
if (isset($oldid) && $oldid != $group->getLabel()) { if (isset($oldid) && $oldid != $group->getLabel()) {
$olddn = $this->getGroupDN($oldid); $olddn = $this->getGroupDN($oldid);
$this->rename($olddn,"cn=".$group->getLabel(),$this->basegroup); $this->rename($olddn, 'cn='.$group->getLabel(), $this->basegroup);
} }
$result = ldap_modify($connection, $dn, $attrs); $result = ldap_modify($connection, $dn, $attrs);
if(!$result) $this->ldapError(); if (!$result) {
$this->ldapError();
}
} }
public function deleteGroup(Group $group){ public function deleteGroup(Group $group)
{
$dn = $this->getGroupDN($group->getLabel()); $dn = $this->getGroupDN($group->getLabel());
return $this->deleteByDN($dn); return $this->deleteByDN($dn);
} }
private function getObjectClassesGroup() { private function getObjectClassesGroup()
$oc = array( {
$oc = [
'top', 'top',
'posixGroup', 'posixGroup',
); ];
return $oc; return $oc;
} }
public function listAttributesGroup() { public function listAttributesGroup()
{
return [ return [
"cn", 'cn',
"gidnumber", 'gidnumber',
"memberuid" 'memberuid',
]; ];
} }
public function fillAttributesGroup(Group $group, array &$attrs) { public function fillAttributesGroup(Group $group, array &$attrs)
{
$attrs['cn'] = $group->getLabel(); $attrs['cn'] = $group->getLabel();
$attrs['gidnumber'] = $group->getId(); $attrs['gidnumber'] = $group->getId();
$attrs['memberuid'] = []; $attrs['memberuid'] = [];
foreach ($group->getUsers() as $usergroup) { foreach ($group->getUsers() as $usergroup) {
array_push($attrs['memberuid'], $usergroup->getUser()->getUsername()); array_push($attrs['memberuid'], $usergroup->getUser()->getUsername());
} }
sort($attrs['memberuid']); sort($attrs['memberuid']);
if(count($attrs['memberuid'])==1) $attrs['memberuid'] = $attrs['memberuid'][0]; if (1 == count($attrs['memberuid'])) {
$attrs['memberuid'] = $attrs['memberuid'][0];
}
} }
public function getGroupDN($id) { public function getGroupDN($id)
{
return 'cn='.$id.','.$this->basegroup; return 'cn='.$id.','.$this->basegroup;
} }
@ -828,39 +948,45 @@ class LdapService
// == Function UserGroup============================================================================================================================================= // == Function UserGroup=============================================================================================================================================
// ================================================================================================================================================================== // ==================================================================================================================================================================
function addUserGroup(UserGroup $usergroup) { public function addUserGroup(UserGroup $usergroup)
{
$dn = $this->basedn; $dn = $this->basedn;
$connection = $this->connect(); $connection = $this->connect();
// On recherche le group en cours // On recherche le group en cours
$criteria = '(cn='.$usergroup->getGroup()->getLabel().')'; $criteria = '(cn='.$usergroup->getGroup()->getLabel().')';
$subbranch = $this->basegroup; $subbranch = $this->basegroup;
$result = $this->search($criteria, array('memberuid'), $subbranch); $result = $this->search($criteria, ['memberuid'], $subbranch);
if (!$this->in_array_r($usergroup->getUser()->getUsername(), $result[0])) { if (!$this->in_array_r($usergroup->getUser()->getUsername(), $result[0])) {
$dn = $this->getGroupDN($usergroup->getGroup()->getLabel()); $dn = $this->getGroupDN($usergroup->getGroup()->getLabel());
$entry['memberuid'] = $usergroup->getUser()->getUsername(); $entry['memberuid'] = $usergroup->getUser()->getUsername();
$result = ldap_mod_add($connection, $dn, $entry); $result = ldap_mod_add($connection, $dn, $entry);
if(!$result) $this->ldapError(); if (!$result) {
$this->ldapError();
}
} }
return $result; return $result;
} }
function delUserGroup(UserGroup $usergroup) { public function delUserGroup(UserGroup $usergroup)
{
$dn = $this->basedn; $dn = $this->basedn;
$connection = $this->connect(); $connection = $this->connect();
// On recherche le group en cours // On recherche le group en cours
$criteria = '(cn='.$usergroup->getGroup()->getLabel().')'; $criteria = '(cn='.$usergroup->getGroup()->getLabel().')';
$subbranch = $this->basegroup; $subbranch = $this->basegroup;
$result = $this->search($criteria, array('memberuid'), $subbranch); $result = $this->search($criteria, ['memberuid'], $subbranch);
if ($this->in_array_r($usergroup->getUser()->getUsername(), $result[0])) { if ($this->in_array_r($usergroup->getUser()->getUsername(), $result[0])) {
$dn = $this->getGroupDN($usergroup->getGroup()->getLabel()); $dn = $this->getGroupDN($usergroup->getGroup()->getLabel());
$entry['memberuid'] = $usergroup->getUser()->getUsername(); $entry['memberuid'] = $usergroup->getUser()->getUsername();
$result = ldap_mod_del($connection, $dn, $entry); $result = ldap_mod_del($connection, $dn, $entry);
if(!$result) $this->ldapError(); if (!$result) {
$this->ldapError();
}
} }
return $result; return $result;

View File

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

View File

@ -4,15 +4,13 @@ namespace App\Service;
use Aws\S3\Exception\S3Exception; use Aws\S3\Exception\S3Exception;
use Exception; use Exception;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class MinioService class MinioService
{ {
const ERR_UNAVAILABLE = 'Service de gestion de fichiers momentanément indisponible.'; public const ERR_UNAVAILABLE = 'Service de gestion de fichiers momentanément indisponible.';
const ERR_FILE_NOT_FOUND = 'messages.minio.404'; public const ERR_FILE_NOT_FOUND = 'messages.minio.404';
private $rootPath; private $rootPath;
private $client; private $client;
@ -26,7 +24,7 @@ class MinioService
{ {
$this->rootPath = $rootPath; $this->rootPath = $rootPath;
$this->minioBucket = $minioBucket; $this->minioBucket = $minioBucket;
$this->minioPathStyle = ($minioPathstyle==1?true:false); $this->minioPathStyle = (1 == $minioPathstyle ? true : false);
$this->minioRoot = $minioRoot; $this->minioRoot = $minioRoot;
$this->client = $this->getClient($minioUrl, $minioKey, $minioSecret, $minioPathstyle, $minioSecure); $this->client = $this->getClient($minioUrl, $minioKey, $minioSecret, $minioPathstyle, $minioSecure);
$this->initBucket(); $this->initBucket();
@ -36,8 +34,8 @@ class MinioService
{ {
// On s'assure que le repertoire temporaire de destination existe bien // On s'assure que le repertoire temporaire de destination existe bien
$fs = new Filesystem(); $fs = new Filesystem();
$tmpdir=$this->rootPath."/var/tmp"; $tmpdir = $this->rootPath.'/var/tmp';
$fs->mkdir($tmpdir."/".dirname($filename)); $fs->mkdir($tmpdir.'/'.dirname($filename));
// Approche repassant par le serveur d'appel // Approche repassant par le serveur d'appel
if (!$usecache || !$fs->exists($tmpdir.'/'.$filename)) { if (!$usecache || !$fs->exists($tmpdir.'/'.$filename)) {
@ -80,8 +78,8 @@ class MinioService
} }
if ($deleteSource) { if ($deleteSource) {
$tmpdir=$this->rootPath."/var/tmp"; $tmpdir = $this->rootPath.'/var/tmp';
@unlink($tmpdir."/".$filename); @unlink($tmpdir.'/'.$filename);
} }
} }
@ -177,8 +175,6 @@ class MinioService
* @param string $filename Nom du fichier dans la réponse * @param string $filename Nom du fichier dans la réponse
* @param bool $returnFile Retourner un fichier ou une réponse * @param bool $returnFile Retourner un fichier ou une réponse
*/ */
protected function getClient($minioUrl, $minioKey, $minioSecret, bool $minioPathstyle, bool $minioSecure) protected function getClient($minioUrl, $minioKey, $minioSecret, bool $minioPathstyle, bool $minioSecure)
{ {
$client = new \Aws\S3\S3Client([ $client = new \Aws\S3\S3Client([

View File

@ -1,4 +1,5 @@
<?php <?php
namespace App\Service; namespace App\Service;
use Symfony\Component\PasswordHasher\Exception\InvalidPasswordException; use Symfony\Component\PasswordHasher\Exception\InvalidPasswordException;
@ -11,11 +12,11 @@ class PasswordEncoder implements LegacyPasswordHasherInterface
public function hash(string $plainPassword, string $salt = null): string public function hash(string $plainPassword, string $salt = null): string
{ {
if ($this->isPasswordTooLong($plainPassword)) { if ($this->isPasswordTooLong($plainPassword)) {
throw new InvalidPasswordException(); throw new InvalidPasswordException();
} }
$hash = "{SSHA}" . base64_encode(pack("H*", sha1($plainPassword . $salt)) . $salt); $hash = '{SSHA}'.base64_encode(pack('H*', sha1($plainPassword.$salt)).$salt);
return $hash; return $hash;
} }

View File

@ -1,9 +1,9 @@
<?php <?php
namespace App\Service; namespace App\Service;
use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\EntityManagerInterface;
use Oneup\UploaderBundle\Event\PostPersistEvent; use Oneup\UploaderBundle\Event\PostPersistEvent;
use App\Service\MinioService;
class UploadListener class UploadListener
{ {
@ -16,20 +16,25 @@ class UploadListener
$this->minio = $minio; $this->minio = $minio;
} }
protected function getHeight($image) { protected function getHeight($image)
{
$size = getimagesize($image); $size = getimagesize($image);
$height = $size[1]; $height = $size[1];
return $height; return $height;
} }
// Cacul de la largeur // Cacul de la largeur
protected function getWidth($image) { protected function getWidth($image)
{
$size = getimagesize($image); $size = getimagesize($image);
$width = $size[0]; $width = $size[0];
return $width; return $width;
} }
protected function resizeImage($image,$width,$height,$scale) { protected function resizeImage($image, $width, $height, $scale)
{
list($imagewidth, $imageheight, $imageType) = getimagesize($image); list($imagewidth, $imageheight, $imageType) = getimagesize($image);
$imageType = image_type_to_mime_type($imageType); $imageType = image_type_to_mime_type($imageType);
$newImageWidth = ceil($width * $scale); $newImageWidth = ceil($width * $scale);
@ -38,16 +43,16 @@ class UploadListener
$source = null; $source = null;
switch ($imageType) { switch ($imageType) {
case "image/gif": case 'image/gif':
$source = imagecreatefromgif($image); $source = imagecreatefromgif($image);
break; break;
case "image/pjpeg": case 'image/pjpeg':
case "image/jpeg": case 'image/jpeg':
case "image/jpg": case 'image/jpg':
$source = imagecreatefromjpeg($image); $source = imagecreatefromjpeg($image);
break; break;
case "image/png": case 'image/png':
case "image/x-png": case 'image/x-png':
$source = imagecreatefrompng($image); $source = imagecreatefrompng($image);
break; break;
} }
@ -58,21 +63,22 @@ class UploadListener
imagecopyresampled($newImage, $source, 0, 0, 0, 0, $newImageWidth, $newImageHeight, $width, $height); imagecopyresampled($newImage, $source, 0, 0, 0, 0, $newImageWidth, $newImageHeight, $width, $height);
switch ($imageType) { switch ($imageType) {
case "image/gif": case 'image/gif':
imagegif($newImage, $image); imagegif($newImage, $image);
break; break;
case "image/pjpeg": case 'image/pjpeg':
case "image/jpeg": case 'image/jpeg':
case "image/jpg": case 'image/jpg':
imagejpeg($newImage, $image, 90); imagejpeg($newImage, $image, 90);
break; break;
case "image/png": case 'image/png':
case "image/x-png": case 'image/x-png':
imagepng($newImage, $image); imagepng($newImage, $image);
break; break;
} }
chmod($image, 0640); chmod($image, 0640);
return $image; return $image;
} }
@ -87,7 +93,7 @@ class UploadListener
$response = $event->getResponse(); $response = $event->getResponse();
$response['file'] = $filename; $response['file'] = $filename;
$this->minio->upload($file,$type."/".$filename,true); $this->minio->upload($file, $type.'/'.$filename, true);
break; break;
} }
} }

View File

@ -1,10 +1,10 @@
<?php <?php
namespace App\Twig; namespace App\Twig;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
use Twig\TwigFunction;
use Ramsey\Uuid\Uuid; use Ramsey\Uuid\Uuid;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
class AppExtension extends AbstractExtension class AppExtension extends AbstractExtension
{ {
@ -17,8 +17,9 @@ class AppExtension extends AbstractExtension
]; ];
} }
public function getUniqueId() { public function getUniqueId()
return str_replace("-","",Uuid::uuid4()); {
return str_replace('-', '', Uuid::uuid4());
} }
public function setContainer($container) public function setContainer($container)

View File

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

View File

@ -1,4 +1,5 @@
<?php <?php
namespace App\Validator; namespace App\Validator;
use Symfony\Component\Validator\Constraint; use Symfony\Component\Validator\Constraint;
@ -21,8 +22,7 @@ class GrouplabelValidator extends ConstraintValidator
// On s'assure que le label ne contient pas des caractères speciaux // On s'assure que le label ne contient pas des caractères speciaux
$string = preg_replace('~[^ éèêôöàïî\'@a-zA-Z0-9._-]~', '', $value); $string = preg_replace('~[^ éèêôöàïî\'@a-zA-Z0-9._-]~', '', $value);
if($string!=$value) if ($string != $value) {
{
$this->context->addViolation($constraint->message); $this->context->addViolation($constraint->message);
} }
} }

View File

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

View File

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

View File

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

View File

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

View File

@ -1,4 +1,5 @@
<?php <?php
namespace App\Validator; namespace App\Validator;
use Symfony\Component\Validator\Constraint; use Symfony\Component\Validator\Constraint;
@ -8,5 +9,5 @@ use Symfony\Component\Validator\Constraint;
*/ */
class Password extends Constraint 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"; 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

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

View File

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

View File

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