dockerisation

This commit is contained in:
2023-12-22 13:53:10 +01:00
parent dfb8eb6236
commit cda63eddba
3260 changed files with 14063 additions and 154683 deletions

View File

@@ -0,0 +1,408 @@
<?php
namespace App\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Console\Input\ArrayInput;
use Ramsey\Uuid\Uuid;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\Id\AssignedGenerator;
use App\Entity\User;
use App\Entity\Config;
class AppInitCommand extends Command
{
private $container;
private $em;
private $output;
private $filesystem;
private $rootlog;
private $appname;
private $appmailnoreply;
public function __construct(ContainerInterface $container,EntityManagerInterface $em)
{
parent::__construct();
$this->container = $container;
$this->em = $em;
}
protected function configure()
{
$this
->setName('app:AppInit')
->setDescription('Init Data for App')
->setHelp('This command Init Data App')
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->output = $output;
$this->filesystem = new Filesystem();
$this->rootlog = $this->container->get('kernel')->getLogDir()."/";
$this->appname = $this->container->getParameter('appName');
$this->appmailnoreply = $this->container->getParameter('appMailnoreply');
$output->writeln('APP = Default Data');
// Création du compte admin si non existant
$this->insertUser("admin","admin");
// colorbgbody = Couleur des fonds de page
$this->insertConfig(
1, // order
"site", // category
"appname", // id
"Titre de votre site", // title
"", // value
"", // defalut
"string", // type,
true, // visible
true, // changeable
false, // required
"", // grouped
"Titre de votre site"
);
$this->insertConfig(
2, // order
"site", // category
"appsubname", // id
"Sous-titre de votre site", // title
"", // value
"", // defalut
"string", // type,
true, // visible
true, // changeable
false, // required
"", // grouped
"Sous-titre de votre site"
);
$this->insertConfig(
3, // order
"site", // category
"appdescription", // id
"Description de votre site", // title
"", // value
"", // defalut
"editor", // type,
true, // visible
true, // changeable
false, // required
"", // grouped
"Description de votre site"
);
$this->insertConfig(
100, // order
"site", // category
"apptheme", // id
"Thème de votre site", // title
"", // value
"", // defalut
"string", // type,
false, // visible
true, // changeable
false, // required
"", // grouped
"Thème de votre site"
);
// colorbgbody = Couleur des fonds de page
$this->insertConfig(
1, // order
"colorbgbody", // category
"colorbgbodydark", // id
"Couleur de fond fonçée", // title
"", // value
"#2574a9", // defalut
"color", // type,
true, // visible
true, // changeable
false, // required
"", // grouped
"La couleur de fond quand le site a besoin d'avoir une couleur de fond foncée"
);
$this->insertConfig(
2, // order
"colorbgbody", // category
"colorbgbodylight", // id
"Couleur de fond claire", // title
"", // value
"#ffffff", // defalut
"color", // type,
true, // visible
true, // changeable
false, // required
"", // grouped
"La couleur de fond quand le site a besoin d'avoir une couleur de fond claire"
);
// colorfttitle = Couleur des fontes titre
$this->insertConfig(
1, // order
"colorfttitle", // category
"colorfttitledark", // id
"Couleur des titres sur fond fonçé", // title
"", // value
"#ffffff", // defalut
"color", // type,
true, // visible
true, // changeable
false, // required
"", // grouped
"La couleur des titres sur fond fonçé"
);
$this->insertConfig(
2, // order
"colorfttitle", // category
"colorfttitlelight", // id
"Couleur des titres sur fond claire", // title
"", // value
"#2574a9", // defalut
"color", // type,
true, // visible
true, // changeable
false, // required
"", // grouped
"La couleur des titres sur fond claire"
);
// colorftbody = Couleur des fontes titre
$this->insertConfig(
1, // order
"colorftbody", // category
"colorftbodydark", // id
"Couleur de la police sur fond fonçé", // title
"", // value
"#ffffff", // defalut
"color", // type,
true, // visible
true, // changeable
false, // required
"", // grouped
"La couleur de la police sur fond fonçé"
);
$this->insertConfig(
2, // order
"colorftbody", // category
"colorftbodylight", // id
"Couleur de la police sur fond claire", // title
"", // value
"#343a40", // defalut
"color", // type,
true, // visible
true, // changeable
false, // required
"", // grouped
"La couleur de la police sur fond claire"
);
// font = nom des polices
$this->insertConfig(
1, // order
"font", // category
"fonttitle", // id
"Police pour les titres", // title
"", // value
"FredokaOne-Regular", // defalut
"font", // type,
true, // visible
true, // changeable
false, // required
"", // grouped
"La couleur de la police de votre site"
);
$this->insertConfig(
2, // order
"font", // category
"fontbody", // id
"Police principale", // title
"", // value
"Roboto-Regular", // defalut
"font", // type,
true, // visible
true, // changeable
false, // required
"", // grouped
"Nom de la police principale"
);
$this->insertConfig(
3, // order
"font", // category
"fontsizeh1", // id
"Taille des titres h1", // title
"", // value
"40", // defalut
"integer", // type,
true, // visible
true, // changeable
false, // required
"", // grouped
"Taille des titres h1 en px"
);
$this->insertConfig(
4, // order
"font", // category
"fontsizeh2", // id
"Taille des titres h2", // title
"", // value
"32", // defalut
"integer", // type,
true, // visible
true, // changeable
false, // required
"", // grouped
"Taille des titres h2 en px"
);
$this->insertConfig(
5, // order
"font", // category
"fontsizeh3", // id
"Taille des titres h3", // title
"", // value
"28", // defalut
"integer", // type,
true, // visible
true, // changeable
false, // required
"", // grouped
"Taille des titres h3 en px"
);
$this->insertConfig(
6, // order
"font", // category
"fontsizeh4", // id
"Taille des titres h4", // title
"", // value
"24", // defalut
"integer", // type,
true, // visible
true, // changeable
false, // required
"", // grouped
"Taille des titres h4 en px"
);
// logo =
$this->insertConfig(
1, // order
"logo", // category
"logodark", // id
"Logo sur fond fonçé", // title
"", // value
"", // defalut
"logo", // type,
true, // visible
true, // changeable
false, // required
"", // grouped
"Logo sur fond fonçé"
);
$this->insertConfig(
2, // order
"logo", // category
"logolight", // id
"Logo sur fond clair", // title
"", // value
"", // defalut
"logo", // type,
true, // visible
true, // changeable
false, // required
"", // grouped
"Logo sur fond clair"
);
$output->writeln('');
return 1;
}
protected function insertUser() {
$metadata = $this->em->getClassMetaData('App:User');
$metadata->setIdGeneratorType(ClassMetadata::GENERATOR_TYPE_NONE);
$metadata->setIdGenerator(new AssignedGenerator());
// Job Récupératoin la table de référence des articles
// Toute les 1mn
$entity = $this->em->getRepository('App:User')->findOneBy(["username"=>"admin"]);
if(!$entity) {
$this->writelnred('Création du compte admin par défaut avec password admin - Veuillez modifier votre password admin après connexion');
$entity = new User;
$key = Uuid::uuid4();
$entity->setId(0);
$entity->setUsername("admin");
$entity->setPassword("admin");
$entity->setFirstname($this->appname);
$entity->setLastname("Admin");
$entity->setEmail($this->appmailnoreply);
$entity->setRoles(["ROLE_ADMIN"]);
$entity->setAvatar("admin.jpg");
$entity->setApiKey($key);
$this->em->persist($entity);
}
// On flush
$this->em->flush();
}
protected function insertConfig($order,$category,$id,$title,$value,$default,$type,$visible,$changeable,$required,$grouped,$help) {
$entity=$this->em->getRepository("App:Config")->find($id);
if(!$entity) {
$entity= new Config();
$entity->setId($id);
$entity->setValue($value);
}
$entity->setDefault($default);
$entity->setCategory($category);
$entity->setOrder($order);
$entity->setTitle($title);
$entity->setType($type);
$entity->setVisible($visible);
$entity->setChangeable($changeable);
$entity->setRequired($required);
$entity->setGrouped($grouped);
$entity->setHelp($help);
$this->em->persist($entity);
$this->em->flush();
}
private function writelnred($string) {
$this->output->writeln('<fg=red>'.$string.'</>');
$this->filesystem->appendToFile($this->rootlog.'cron.log', $string."\n");
}
private function writeln($string) {
$this->output->writeln($string);
$this->filesystem->appendToFile($this->rootlog.'cron.log', $string."\n");
}
}

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

@@ -0,0 +1,165 @@
<?php
namespace App\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Command\LockableTrait;
use App\Entity\Cron;
class CronCommand extends Command
{
private $container;
private $em;
private $output;
private $filesystem;
private $rootlog;
use LockableTrait;
public function __construct(ContainerInterface $container,EntityManagerInterface $em)
{
parent::__construct();
$this->container = $container;
$this->em = $em;
}
protected function configure()
{
$this
->setName('app:Cron')
->setDescription('Execution of the cron command')
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->output = $output;
$this->filesystem = new Filesystem();
$this->rootlog = $this->container->get('kernel')->getLogDir()."/";
$appCron = $this->container->getParameter('appCron');
if(!$appCron)
{
return 0;
}
if (!$this->lock()) {
$this->output->writeln("CRON LOCK");
return 0;
}
$crons = $this->em->getRepository('App:Cron')->toexec();
$i=0;
if($crons) {
$now=new \DateTime();
$this->writelnred('');
$this->writelnred('');
$this->writelnred('');
$this->writelnred('');
$this->writelnred('==========================================================================================================');
$this->writelnred('== CRON ==================================================================================================');
$this->writelnred('==========================================================================================================');
$this->writeln ('Date = '.$now->format('Y-m-d H:i:s'));
$this->writeln ('Application = '.$this->container->getParameter("appName"));
}
foreach($crons as $cron) {
$i++;
// Id du cron
$idcron = $cron->getId();
// Flag d'execution en cours
$now=new \DateTime();
$cron->setStartexecdate($now);
//$cron->setStatut(1);
$this->em->persist($cron);
$this->em->flush();
// Récupération de la commande
$command = $this->getApplication()->find($cron->getCommand());
// Réccuépration des parametres
$jsonparameter=json_decode($cron->getJsonargument(),true);
// Parametre id du cron actuel
$jsonparameter["cronid"]=$cron->getId();
// Parametre si dernière execution
$lastchance=false;
if($cron->getRepeatcall()>0)
$lastchance=($cron->getRepeatexec()+1==$cron->getRepeatcall());
$jsonparameter["lastchance"]=$lastchance;
// Formater la chaine de parametre
$parameter = new ArrayInput($jsonparameter);
// Executer la commande
$returnCode=false;
try{
$returnCode = $command->run($parameter, $output);
// Revenir sur le cron encours à cause du clear du manager présent dans la synchro
// Sinon le manager se pomme et génère des nouveaux enregistrement plutot que mettre à jour celui en cours
$cron=$this->em->getRepository('App:Cron')->find($idcron);
}
catch(\Exception $e) {
$this->writelnred("JOB EN ERREUR");
}
// Flag de fin d'execution
$now=new \DateTime();
$cron->setEndexecdate($now);
// Date prochaine execution
if($cron->getrepeatinterval()>=0) {
// Si interval par heure
if(fmod($cron->getRepeatinterval(),3600)==0)
$next=clone $cron->getNextexecdate();
else
$next=new \DateTime();
$next->add(new \DateInterval('PT'.$cron->getRepeatinterval().'S'));
$cron->setNextexecdate($next);
}
// Statut OK/KO/Retry
if($returnCode!="retry"||!$returnCode) {
$cron->setStatut(2);
if($returnCode!=1) {
$cron->setStatut(3);
if($cron->getRepeatcall()>0) $cron->setRepeatexec($cron->getRepeatexec()+1);
}
}
$this->em->persist($cron);
$this->em->flush();
}
if($crons) {
$this->writelnred("==");
$this->writelnred("FIN CRON");
$this->writelnred("==");
$this->writelnred("");
}
return 1;
}
private function writelnred($string) {
$this->output->writeln('<fg=red>'.$string.'</>');
$this->filesystem->appendToFile($this->rootlog.'cron.log', $string."\n");
}
private function writeln($string) {
$this->output->writeln($string);
$this->filesystem->appendToFile($this->rootlog.'cron.log', $string."\n");
}
}

View File

@@ -0,0 +1,119 @@
<?php
namespace App\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Filesystem\Filesystem;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\Id\AssignedGenerator;
use App\Entity\Cron;
class CronInitCommand extends Command
{
private $container;
private $em;
private $output;
private $filesystem;
private $rootlog;
public function __construct(ContainerInterface $container,EntityManagerInterface $em)
{
parent::__construct();
$this->container = $container;
$this->em = $em;
}
protected function configure()
{
$this
->setName('app:CronInit')
->setDescription('Init Data for Cron')
->setHelp('This command Init Data Cron')
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$appCron = $this->container->getParameter('appCron');
$this->rootlog = $this->container->get('kernel')->getLogDir()."/";
if(!$appCron)
return false;
$output->writeln('CRON = Default Data');
$this->insertCron();
$output->writeln('');
return 1;
}
protected function insertCron() {
$metadata = $this->em->getClassMetaData('App:Cron');
// Job Mail
// Toute les minutes
$entity = $this->em->getRepository('App:Cron')->findOneBy(["command"=>"app:sendMail"]);
if(!$entity) {
$entity = new Cron;
$entity->setCommand("app:sendMail");
$entity->setDescription("Execution du spool de mail en attente");
$entity->setStatut(2);
$entity->setRepeatcall(0);
$entity->setRepeatexec(0);
$entity->setRepeatinterval(60);
$entity->setNextexecdate($entity->getSubmitdate());
$entity->setJsonargument('{"message-limit":"100","env":"prod"}');
$this->em->persist($entity);
}
// Job de purge des fichiers obsolète
// Toute les 24h à 3h00
$entity = $this->em->getRepository('App:Cron')->findOneBy(["command"=>"app:purgeFile"]);
if(!$entity) {
$entity = new Cron;
$nextdate=$entity->getSubmitdate();
$nextdate->setTime(3,0);
$entity->setCommand("app:purgeFile");
$entity->setDescription("Suppression des fichiers obsolètes");
$entity->setStatut(2);
$entity->setRepeatcall(0);
$entity->setRepeatexec(0);
$entity->setRepeatinterval(86400);
$entity->setNextexecdate($nextdate);
$this->em->persist($entity);
}
// Job Dump
// Toute les 24h à 2h00
$entity = $this->em->getRepository('App:Cron')->findOneBy(["command"=>"app:dumpBdd"]);
if(!$entity) {
$entity = new Cron;
$nextdate=$entity->getSubmitdate();
$nextdate->setTime(2,0);
$entity->setCommand("app:dumpBdd");
$entity->setDescription("Sauvegarde de la BDD");
$entity->setStatut(2);
$entity->setRepeatcall(0);
$entity->setRepeatexec(0);
$entity->setRepeatinterval(86400);
$entity->setNextexecdate($nextdate);
$this->em->persist($entity);
}
// On flush
$this->em->flush();
}
}

View File

@@ -0,0 +1,92 @@
<?php
namespace App\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Security\Core\Encoder\EncoderFactory;
use Symfony\Component\Security\Core\Encoder\MessageDigestPasswordEncoder;
use Symfony\Component\Finder\Finder;
class DumpBddCommand extends Command
{
private $container;
private $em;
private $output;
private $filesystem;
private $rootlog;
private $byexec;
public function __construct(ContainerInterface $container,EntityManagerInterface $em)
{
parent::__construct();
$this->container = $container;
$this->em = $em;
}
protected function configure()
{
$this
->setName('app:dumpBdd')
->setDescription('Sauvegarde de la BDD')
->setHelp('Sauvegarde de la BDD')
->addArgument('cronid', InputArgument::OPTIONAL, 'ID Cron Job')
->addArgument('lastchance', InputArgument::OPTIONAL, 'Lastchance to run the cron')
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->output = $output;
$this->filesystem = new Filesystem();
$this->rootlog = $this->container->get('kernel')->getLogDir()."/";
$name = $this->container->getParameter('appName');
$this->writelnred('');
$this->writelnred('== app:dumpBdd');
$this->writelnred('==========================================================================================================');
$this->datahost = $this->container->getParameter('databaseHost');
$this->database = $this->container->getParameter('databaseName') ;
$this->username = $this->container->getParameter('databaseUser') ;
$this->password = $this->container->getParameter('databasePassword') ;
$cmd = sprintf('mysqldump -h %s -B %s -u %s --password=%s'
, $this->datahost
, $this->database
, $this->username
, $this->password
);
$result = $this->runCommand($cmd);
if($result['exit_status'] == 0) {
$this->filesystem->dumpFile($this->rootlog.$name.".sql", implode('', $result['output']));
}
$this->writeln('');
return 1;
}
protected function runCommand($command)
{
$command .=" >&1";
exec($command, $output, $exit_status);
return array(
"output" => $output
, "exit_status" => $exit_status
);
}
private function writelnred($string) {
$this->output->writeln('<fg=red>'.$string.'</>');
$this->filesystem->appendToFile($this->rootlog.'cron.log', $string."\n");
}
private function writeln($string) {
$this->output->writeln($string);
$this->filesystem->appendToFile($this->rootlog.'cron.log', $string."\n");
}
}

View File

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

View File

@@ -0,0 +1,91 @@
<?php
namespace App\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Filesystem\Filesystem;
use Ramsey\Uuid\Uuid;
use App\Entity\Script;
class ScriptCommand extends Command
{
private $container;
private $em;
private $output;
private $filesystem;
private $rootlog;
public function __construct(ContainerInterface $container,EntityManagerInterface $em)
{
parent::__construct();
$this->container = $container;
$this->em = $em;
}
protected function configure()
{
$this
->setName('app:Script')
->setDescription('Script to call')
->setHelp('Script to call')
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->output = $output;
$this->filesystem = new Filesystem();
$this->rootlog = $this->container->get('kernel')->getLogDir()."/";
$output->writeln('APP = Scripts');
$this->callscript("addapikey");
$output->writeln('');
return 1;
}
private function callscript($name) {
$script=$this->em->getRepository("App:Script")->findOneBy(["name"=>$name]);
if(!$script) {
//$this->writelnred("== SCRIPT = ".$name);
$this->$name();
$script=new Script();
$script->setName($name);
$this->em->persist($script);
$this->em->flush();
$this->writeln("");
}
}
private function addapikey() {
$users=$this->em->getRepository("App:User")->findBy(["apikey"=>null]);
foreach($users as $user) {
$key = Uuid::uuid4();
$user->setApikey($key);
$this->em->persist($user);
$this->em->flush();
}
}
private function writelnred($string) {
$this->output->writeln('<fg=red>'.$string.'</>');
$this->filesystem->appendToFile($this->rootlog.'cron.log', $string."\n");
}
private function writeln($string) {
$this->output->writeln($string);
$this->filesystem->appendToFile($this->rootlog.'cron.log', $string."\n");
}
}

View File

@@ -0,0 +1,87 @@
<?php
namespace App\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Security\Core\Encoder\EncoderFactory;
use Symfony\Component\Security\Core\Encoder\MessageDigestPasswordEncoder;
class SendMailCommand extends Command
{
private $container;
private $em;
private $output;
private $filesystem;
private $rootlog;
public function __construct(ContainerInterface $container,EntityManagerInterface $em)
{
parent::__construct();
$this->container = $container;
$this->em = $em;
}
protected function configure()
{
$this
->setName('app:sendMail')
->setDescription('Envoi des mails')
->setHelp('Envoi des mails')
->addArgument('message-limit', InputArgument::OPTIONAL, 'limit message Mail')
->addArgument('env', InputArgument::OPTIONAL, 'env Mail')
->addArgument('cronid', InputArgument::OPTIONAL, 'ID Cron Job')
->addArgument('lastchance', InputArgument::OPTIONAL, 'Lastchance to run the cron')
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->output = $output;
$this->filesystem = new Filesystem();
$this->rootlog = $this->container->get('kernel')->getLogDir()."/";
$this->writelnred('');
$this->writelnred('== app:sendMail');
$this->writelnred('==========================================================================================================');
$appMailmethod=$this->container->getParameter("appMailmethod");
$command = $this->getApplication()->find("swiftmailer:spool:send");
$tbparameter["--message-limit"]=100;
$tbparameter["--env"]="prod";
$tbparameter["--time-limit"]=5;
if($appMailmethod=="sendmail") $tbparameter["--transport"]="app.sendmail.transport";
$parameter = new ArrayInput($tbparameter);
try{
$returnCode = $command->run($parameter, $output);
}
catch(\Exception $e) {
$this->writeln("");
$this->writelnred("Impossible d'envoyer des mails");
$this->writeln("");
return 0;
}
$this->writeln("");
return 1;
}
private function writelnred($string) {
$this->output->writeln('<fg=red>'.$string.'</>');
$this->filesystem->appendToFile($this->rootlog.'cron.log', $string."\n");
}
private function writeln($string) {
$this->output->writeln($string);
$this->filesystem->appendToFile($this->rootlog.'cron.log', $string."\n");
}
}

View File

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

View File

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

View File

@@ -0,0 +1,737 @@
<?php
namespace App\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Security\Core\Encoder\EncoderFactory;
use Symfony\Component\Security\Core\Encoder\MessageDigestPasswordEncoder;
use Ramsey\Uuid\Uuid;
use App\Entity\Group;
use App\Entity\User;
class SynchroUsersCommand extends Command
{
private $container;
private $em;
private $output;
private $filesystem;
private $rootlog;
private $ldap;
private $ldap_basedn;
private $ldapgroups=[];
public function __construct(ContainerInterface $container,EntityManagerInterface $em)
{
parent::__construct();
$this->container = $container;
$this->em = $em;
}
protected function configure()
{
$this
->setName('app:synchroUsers')
->setDescription('Synchronisation des Utilisateurs')
->setHelp('Synchronisation des Utilisateurs')
->addArgument('simulate', InputArgument::OPTIONAL, 'true to simulate / false to run')
->addArgument('cronid', InputArgument::OPTIONAL, 'ID Cron Job')
->addArgument('lastchance', InputArgument::OPTIONAL, 'Lastchance to run the cron')
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->output = $output;
$this->filesystem = new Filesystem();
$this->rootlog = $this->container->get('kernel')->getLogDir()."/";
$this->writelnred('');
$this->writelnred('== app:synchroUsers');
$this->writelnred('==========================================================================================================');
$simulate = $input->getArgument('simulate');
if($simulate=="") $simulate="true";
if($simulate!="true"&&$simulate!="false") {
$this->writeln('Paramétre incorrect');
return;
}
$simulate=($simulate=="true");
$this->writeln('');
if($simulate) $this->writeln('** SIMULATION');
else $this->writeln('** REEL');
// Synchro
if($this->container->getParameter('appMasteridentity')=="LDAP")
$this->synchroLdap($simulate);
else
$this->synchroNinegate($simulate);
return 1;
}
protected function synchroLdap($simulate) {
$this->writeln('');
$this->writeln('=====================================================');
$this->writeln('== SYNCHONISATION ANNUAIRE ==========================');
$this->writeln('=====================================================');
$this->ldap = $this->container->get('app.ldap.service');
$this->writeln('');
$this->writeln('=====================================================');
$this->writeln('== SYNCHONISATION LDAP TO BUNDLE ====================');
$this->writeln('=====================================================');
$this->ldap_basedn = $this->container->getParameter('ldapBasedn');
$ldap_username = $this->container->getParameter('ldapUsername');
$ldap_firstname = $this->container->getParameter('ldapFirstname');
$ldap_lastname = $this->container->getParameter('ldapLastname');
$ldap_email = $this->container->getParameter('ldapEmail');
$ldap_admins = $this->container->getParameter('ldapAdmins');
$ldap_model = $this->container->getParameter('ldapModel');
$fieldstoread = array($ldap_username,$ldap_firstname,$ldap_lastname,$ldap_email);
$ldapusers = array();
$ldapmails = array();
if($ldap_model=="scribe") {
$this->writeln('');
$this->writeln('== SCRIBE ===========================================');
$this->writeln('');
$this->writeln('== PROFILS ==========================================');
// Eleves
$ldapfilter="(&(uid=*)(ENTPersonProfils=eleve))";
$label="PROFIL - Elèves";
$this->writeln(" - $label");
if(!$simulate) $this->addmodGroup($label,$ldapfilter,false);
// Enseignants
$ldapfilter="(|(&(uid=*)(ENTPersonProfils=enseignant))(&(uid=*)(typeadmin=0))(&(uid=*)(typeadmin=2)))";
$label="PROFIL - Enseignants";
$this->writeln(" - $label");
if(!$simulate) $this->addmodGroup($label,$ldapfilter,true);
// Responsables
$ldapfilter="(&(uid=*)(ENTPersonProfils=responsable))";
$label="PROFIL - Responsables";
$this->writeln(" - $label");
if(!$simulate) $this->addmodGroup($label,$ldapfilter,false);
// Administratifs
$ldapfilter="(&(uid=*)(ENTPersonProfils=administratif))";
$label="PROFIL - Administratifs";
$this->writeln(" - $label");
if(!$simulate) $this->addmodGroup($label,$ldapfilter,true);
// Classes
$this->writeln('');
$this->writeln('== CLASSES ==========================================');
$results = $this->ldap->search("type=Classe", ['cn','description','gidNumber'], $this->ldap_basedn);
foreach($results as $result) {
$cn=$result["cn"];
$ldapfilter="(|(&(type=Classe)(cn=$cn))(&(type=Equipe)(cn=profs-$cn))(&(ENTPersonProfils=Administratif)(divcod=$cn)))";
$label="CLASSE - ".$result["cn"];
$this->writeln(" - $label");
if(!$simulate) $this->addmodGroup($label,$ldapfilter,true);
}
// Options
$this->writeln('');
$this->writeln('== OPTIONS ==========================================');
$cn=$result["cn"];
$results = $this->ldap->search("type=Option", ['cn','description','gidNumber'], $this->ldap_basedn);
foreach($results as $result) {
$ldapfilter="(|(&(type=Option)(cn=$cn))(&(type=Equipe)(cn=profs-$cn))(&(ENTPersonProfils=Administratif)(divcod=$cn)))";
$label="OPTION - ".$result["cn"];
$this->writeln(" - $label");
if(!$simulate) $this->addmodGroup($label,$ldapfilter,true);
}
$ldap_filtergroup="(type=Groupe)";
$ldap_filteruser="(&(uid=*)(objectclass=inetOrgPerson)(!(description=Computer)))";
}
else {
$ldap_filtergroup=$this->container->getParameter('ldapFiltergroup');
$ldap_filteruser=$this->container->getParameter('ldapFilteruser');
}
// Groupes
$this->writeln('');
$this->writeln('== GROUPES ==========================================');
$results = $this->ldap->search($ldap_filtergroup, ['cn','description','gidNumber'], $this->ldap_basedn);
foreach($results as $result) {
$cn=$result["cn"];
$ldapfilter="(&(&".$ldap_filtergroup.")(cn=$cn))";
$label="GROUPE - ".$result["cn"];
$this->writeln(" - $label");
if(!$simulate) $this->addmodGroup($label,$ldapfilter,true);
}
$this->writeln('');
$this->writeln('== USERS ============================================');
// On stocke tout les email déjà existant
$this->writeln('== Stocker les emails utilisateurs existants');
$users=$this->em->createQueryBuilder()->select('table.email')->from('App:User','table')->getQuery()->getArrayResult();
foreach($users as $user) {
array_push($ldapmails,$user["email"]);
}
// Sur l'ensemble des utilisateurs de l'anuaire
$this->writeln("== Récupération des utilisateurs de l'annuaire");
$results = $this->ldap->search($ldap_filteruser, $fieldstoread, $this->ldap_basedn);
$nbuserstotal=count($results);
$nbusers=0;
$tberrors=[];
// Pour chaque utilisateur ldap
$this->writeln('== Traitement des utilisateurs');
foreach($results as $result) {
// Compteur de users
$nbusers++;
// Formatage du résultat
if(is_array($result[$ldap_username])) {
$result[$ldap_username]=$result[$ldap_username][0];
}
$result[$ldap_username]=utf8_encode($result[$ldap_username]);
if(!isset($result[$ldap_lastname])) $result[$ldap_lastname] = "";
if(!isset($result[$ldap_firstname])) $result[$ldap_firstname] = "";
if(!array_key_exists($ldap_email,$result)||empty($result[$ldap_email])) $result[$ldap_email]=$result[$ldap_username]."@nomail.fr";
$result[$ldap_email]=strtolower($result[$ldap_email]);
$result[$ldap_email]=utf8_encode($result[$ldap_email]);
// On sauvegarde ce user
if(in_array($result[$ldap_username],$ldapusers)) {
$this->writelnred(" - Création dans Bundle impossible >> ".$result[$ldap_username]." deux users avec le meme uid");
continue;
}
array_push($ldapusers,$result[$ldap_username]);
// Création ou Modification du user
$user=$this->em->getRepository('App:User')->findOneBy(array('username' => $result[$ldap_username]));
if(!$user) {
if(empty($result[$ldap_email]))
array_push($tberrors," - Création dans Bundle impossible >> ".$result[$ldap_username]." sans email");
else {
if(in_array($result[$ldap_email],$ldapmails))
array_push($tberrors," - Création dans Bundle impossible >> ".$result[$ldap_username]." un autre utilisateur a déjà ce mail = ".$result[$ldap_email]);
else {
array_push($ldapmails,$result[$ldap_email]);
$this->writeln(" - Création dans Bundle >> ".$result[$ldap_username]);
if(!$simulate) $this->addUser($result[$ldap_username],$result[$ldap_firstname],$result[$ldap_lastname],$result[$ldap_email],$ldap_admins);
}
}
}
else {
$toadmin=false;
if(in_array($result[$ldap_username],$ldap_admins)&&!in_array("ROLE_ADMIN",$user->getRoles()))
$toadmin=true;
if($user->getLastname()!=$result[$ldap_lastname]||$user->getFirstname()!=$result[$ldap_firstname]||$user->getEmail()!=$result[$ldap_email]||$toadmin) {
$usermail=$this->em->getRepository('App:User')->findOneBy(array('email' => $result[$ldap_email]));
if($usermail&&$usermail!=$user) {
array_push($tberrors," - Modification dans Bundle impossible >> ".$result[$ldap_username]." un autre utilisateur a déjà ce mail = ".$result[$ldap_email]);
}
else {
$this->writeln(" - Modification dans Bundle >> ".$result[$ldap_username]);
if(!$simulate) $this->modUser($user,$result[$ldap_username],$result[$ldap_firstname],$result[$ldap_lastname],$result[$ldap_email],$ldap_admins);
}
}
}
if($nbusers%1000==0) $this->writeln(" == Nombre d'utilisateurs traités = $nbusers sur $nbuserstotal ==");
}
if(!$simulate) {
$this->writeln(" == Nombre d'utilisateurs traités = $nbusers sur $nbuserstotal ==");
$this->em->flush();
}
foreach($tberrors as $error) {
$this->writelnred(" == ERROR == $error");
}
$this->writeln('');
$this->writeln('== USERS GROUP ======================================');
$groups=$this->em->getRepository('App:Group')->findAll();
foreach($groups as $group) {
if(!$group->getldapfilter()) continue;
$ldapusersgroup=array();
$ldapfilter=$group->getLdapfilter();
$this->writeln('');
$this->writeln('== '.$group->getName());
if(!is_null($ldapfilter)) {
$results = $this->ldap->search($ldapfilter,[$ldap_username,"memberuid"] , $this->ldap_basedn);
foreach($results as $result) {
if(isset($result["memberuid"])) {
// Si memberid est un tableau il y a plusieur user dedans
if(is_array($result["memberuid"])) {
foreach($result["memberuid"] as $key => $value) {
if(is_int($key)) {
$user=$this->em->getRepository('App:User')->findOneBy(array('username' => $value));
if($user) {
array_push($ldapusersgroup,$value);
$this->writeln(" - Rattacher >> ".$value);
if(!$simulate) $this->addtoGroup($user,$group);
}
}
}
}
// sinon m'a qu'un seul uid
else {
$user=$this->em->getRepository('App:User')->findOneBy(array('username' => $result["memberuid"]));
if($user) {
array_push($ldapusersgroup,$result["memberuid"]);
$this->writeln(" - Rattacher >> ".$result["memberuid"]);
if(!$simulate) $this->addtoGroup($user,$group);
}
}
}
if(isset($result[$ldap_username])) {
$user=$this->em->getRepository('App:User')->findOneBy(array('username' => $result[$ldap_username]));
if($user) {
array_push($ldapusersgroup,$result[$ldap_username]);
$this->writeln(" - Rattacher >> ".$result[$ldap_username]);
if(!$simulate) $this->addtoGroup($user,$group);
}
}
}
foreach($group->getUsers() as $member) {
if(!in_array($member->getUsername(),$ldapusersgroup)) {
$this->writeln(" - Détattacher >> ".$member->getUsername());
if(!$simulate) {
$this->em->remove($member);
$this->em->flush();
}
}
}
}
}
$this->writeln('');
$this->writeln('=====================================================');
$this->writeln('== SYNCHONISATION BUNDLE TO LDAP ====================');
$this->writeln('=====================================================');
$this->writeln('');
$this->writeln('== USERS ============================================');
// Pour chaque utilisateur de la base
//$users=$this->em->getRepository('App:User')->findAll();
$datas=$this->em->createQueryBuilder()->select('table.id,table.username')->from('App:User','table')->getQuery()->getArrayResult();
$nbusers=0;
// tentative d'optimisation
$flipped = array_flip($ldapusers);
foreach($datas as $data) {
$nbusers++;
// Si l'utilisateur n'est pas dans la liste des users ldap : on le supprime
if(!isset($flipped[$data["username"]])) {
$user=$this->em->getRepository('App:User')->find($data["id"]);
if($user->getUsername()=="admin")
$this->writeln(" - Ne jamais supprimer >> ".$user->getUsername());
else {
$this->writeln(" - Suppression dans Bundle >> ".$user->getUsername());
if(!$simulate) {
$this->em->remove($user);
$this->em->flush();
}
}
}
else {
//on peut unset les recherches suivantes seront plus rapide
unset($flipped[$data["username"]]);
}
if($nbusers%1000==0) $this->writelnred(" == Nombre d'utilisateurs traités = $nbusers==");
}
$this->writeln('');
$this->writeln('== GROUPS ============================================');
$groups=$this->em->getRepository("App:Group")->findAll();
foreach($groups as $group) {
if($group->getIdexternal()) {
$this->writeln(" - Suppression dans Bundle >> ".$group->getName());
if(!$simulate) {
$this->em->remove($group);
$this->em->flush();
}
}
if(!$group->getLdapfilter()) continue;
if(!in_array($group->getId(),$this->ldapgroups)) {
$this->writeln(" - Suppression dans Bundle >> ".$group->getName());
if(!$simulate) {
$this->em->remove($group);
$this->em->flush();
}
}
}
$this->writeln('');
}
protected function synchroNinegate($simulate) {
$this->writeln('');
$this->writeln('=====================================================');
$this->writeln('== SYNCHONISATION NINEGATE ==========================');
$this->writeln('=====================================================');
$this->writeln('');
$this->writeln('=====================================================');
$this->writeln('== SYNCHONISATION NINEGATE TO BUNDLE ================');
$this->writeln('=====================================================');
$appmasterurl = $this->container->getParameter("appMasterurl");
$appmasterkey = $this->container->getParameter("appMasterkey");
// Généraltion de l'urol de communication
if(stripos($appmasterurl,"/")===0) {
$url="https://".$this->container->getParameter("appWeburl").$appmasterurl;
}
else
$url=$appmasterurl;
// Entete
$headers = ['Accept' => 'application/json'];
$query = [];
// Paramétrage unirest
\Unirest\Request::verifyPeer(false);
\Unirest\Request::verifyHost(false);
\Unirest\Request::timeout(5);
// Login sans proxy
try{
$response = \Unirest\Request::post($url.'/rest/login',$headers,["key"=>$appmasterkey]);
}
catch (\Exception $e) {
// On tente avec le proxy s'il y en a un
$proxyUse = $this->container->getParameter("proxyUse");
if($proxyUse) {
$proxyHost = $this->container->getParameter("proxyHost");
$proxyPort = $this->container->getParameter("proxyPort");
\Unirest\Request::proxy($proxyHost, $proxyPort, CURLPROXY_HTTP, true);
try{
$response = \Unirest\Request::post($url.'/rest/login/'.$appmasterkey,$headers,$query);
}
catch (\Exception $e) {
die("Erreur de communication API = ".$e->getMessage()."\n");
}
}
else {
die("Erreur de communication API = ".$e->getMessage()."\n");
}
}
if($response->code!="200")
die("Erreur sur clé API\n");
$this->writeln('');
$this->writeln('== GROUPS ============================================');
// Récupération des informations groups issus du masteridentity
try{
$response = \Unirest\Request::post($url.'/rest/groups',$headers,["key"=>$appmasterkey]);
}
catch (\Exception $e) {
die("Erreur de communication API = ".$e->getMessage()."\n");
}
$lstgroups=[];
if($response->code=="200" && is_object($response->body)) {
$apigroups=$response->body;
foreach($apigroups as $apigroup) {
array_push($lstgroups,$apigroup->id);
$group=$this->em->getRepository("App:Group")->findOneBy(["idexternal"=>$apigroup->id]);
$this->writeln(" - ".$apigroup->name);
if(!$simulate) {
if(!$group) {
$group = new Group();
$group->setIdexternal($apigroup->id);
}
$group->setName($apigroup->name);
$this->em->persist($group);
$this->em->flush();
}
}
}
else die("Erreur de communication = ".print_r($response,true));
$this->writeln('');
$this->writeln('== USERS ============================================');
// Récupération des informations utilisateurs issus du masteridentity
try{
$response = \Unirest\Request::post($url.'/rest/users',$headers,["key"=>$appmasterkey]);
}
catch (\Exception $e) {
die("Erreur de communication API = ".$e->getMessage()."\n");
}
$lstusers=[];
if($response->code=="200"&&is_object($response->body)) {
$apiusers=$response->body;
foreach($apiusers as $apiuser) {
array_push($lstusers,$apiuser->username);
$user=$this->em->getRepository("App:User")->findOneBy(["username"=>$apiuser->username]);
$this->writeln(" - ".$apiuser->username);
if(!$simulate) {
if(!$user) {
$user = new User();
$key = Uuid::uuid4();
$user->setUsername($apiuser->username);
$user->setPassword("NOPASSWORD");
$user->setApiKey($key);
}
$user->setLastname($apiuser->lastname);
$user->setFirstname($apiuser->firstname);
$user->setEmail($apiuser->email);
$user->setAvatar($apiuser->avatar);
if(in_array($apiuser->username,$this->container->getParameter("ldapAdmins")))
$role="ROLE_ADMIN";
else
$role=($apiuser->role=="ROLE_ANIM"?"ROLE_MASTER":$apiuser->role);
if(!$user->hasRole($role)) {
$roles=$user->getRoles();
array_push($roles,$role);
$user->setRoles($roles);
}
$this->em->persist($user);
$this->em->flush();
}
}
}
else die("Erreur de communication");
$this->writeln('');
$this->writeln('== USERS GROUP ======================================');
$groups=$this->em->getRepository('App:Group')->findAll();
$tabgroups = json_decode(json_encode($apigroups), true);
foreach($groups as $group) {
if(!$group->getIdexternal()) continue;
$this->writeln($group->getName());
$usergroups=[];
if($tabgroups[$group->getIdexternal()])
$usergroups = $tabgroups[$group->getIdexternal()]["users"];
$tbusers=[];
foreach($usergroups as $user) {
array_push($tbusers,$user["username"]);
// On recherche le user en question
$user=$this->em->getRepository("App:User")->findOneBy(["username"=>$user["username"]]);
if($user) {
$this->writeln(" - Rattachement ".$user->getUsername());
if(!$simulate) {
if(!$group->getUsers()->contains($user)) {
$group->addUser($user);
}
}
}
}
foreach($group->getUsers() as $user) {
if(!in_array($user->getUsername(),$tbusers)) {
$this->writeln(" - Détachement ".$user->getUsername());
if(!$simulate) {
$group->removeUser($user);
}
}
}
$this->em->persist($group);
$this->em->flush();
}
$this->writeln('');
$this->writeln('=====================================================');
$this->writeln('== SYNCHONISATION BUNDLE TO NINEGATE ================');
$this->writeln('=====================================================');
$this->writeln('');
$this->writeln('== USERS ============================================');
// Pour chaque utilisateur de la base
$users=$this->em->getRepository("App:User")->findAll();
foreach($users as $user) {
if(!in_array($user->getUsername(),$lstusers)) {
if($user->getUsername()=="admin")
$this->writeln(" - Ne jamais supprimer >> ".$user->getUsername());
else {
$this->writeln(" - Suppression dans Bundle >> ".$user->getUsername());
if(!$simulate) {
$this->em->remove($user);
$this->em->flush();
}
}
}
}
$this->writeln('');
$this->writeln('== GROUPS ============================================');
$groups=$this->em->getRepository("App:Group")->findAll();
foreach($groups as $group) {
if($group->getLdapfilter()) {
$this->writeln(" - Suppression dans Bundle >> ".$group->getName());
if(!$simulate) {
$this->em->remove($group);
$this->em->flush();
}
}
if(!$group->getIdexternal()) continue;
if(!in_array($group->getIdexternal(),$lstgroups)) {
$this->writeln(" - Suppression dans Bundle >> ".$group->getName());
if(!$simulate) {
$this->em->remove($group);
$this->em->flush();
}
}
}
$this->writeln('');
}
private function writelnred($string) {
$this->output->writeln('<fg=red>'.$string.'</>');
$this->filesystem->appendToFile($this->rootlog.'cron.log', $string."\n");
}
private function writeln($string) {
$this->output->writeln($string);
$this->filesystem->appendToFile($this->rootlog.'cron.log', $string."\n");
}
protected function addmodGroup($label,$ldapfilter,$fgcanshare) {
$group=$this->em->getRepository('App:Group')->findOneBy(array('name' => $label));
if(!$group) {
$group=new Group();
}
$group->setName($label);
$group->setLdapfilter($ldapfilter);
$this->em->persist($group);
$this->em->flush();
array_push($this->ldapgroups,$group->getId());
}
protected function addtoGroup($user,$group) {
if(!$group->getUsers()->contains($user)) {
$group->addUser($user);
$this->em->persist($group);
$this->em->flush();
}
}
protected function addUser($username,$firstname,$lastname,$email,$usersadmin) {
$user = new User();
$key = Uuid::uuid4();
$user->setUsername($username);
$user->setPassword("NOPASSWORD");
$user->setLastname($lastname);
$user->setFirstname($firstname);
$user->setEmail($email);
$user->setApiKey($key);
// Definition du role
if(in_array($username,$usersadmin))
$role="ROLE_ADMIN";
else {
$ldapfilter="(|(&(uid=".$user->getUsername().")(ENTPersonProfils=enseignant))(&(uid=".$user->getUsername().")(typeadmin=0))(&(uid=".$user->getUsername().")(typeadmin=2)))";
$results = $this->ldap->search($ldapfilter, ['uid'], $this->ldap_basedn);
if($results) $role="ROLE_MASTER";
else $role="ROLE_USER";
}
if(!$user->hasRole($role)) {
$roles=$user->getRoles();
array_push($roles,$role);
$user->setRoles($roles);
}
$this->em->persist($user);
$this->em->flush();
}
protected function modUser($user,$username,$firstname,$lastname,$email,$usersadmin) {
$user->setLastname($lastname);
$user->setFirstname($firstname);
$user->setEmail($email);
// Definition du role
if(in_array($username,$usersadmin))
$role="ROLE_ADMIN";
else {
$ldapfilter="(|(&(uid=".$user->getUsername().")(ENTPersonProfils=enseignant))(&(uid=".$user->getUsername().")(typeadmin=0))(&(uid=".$user->getUsername().")(typeadmin=2)))";
$results = $this->ldap->search($ldapfilter, ['uid'], $this->ldap_basedn);
if($results) $role="ROLE_MASTER";
else $role="ROLE_USER";
}
if(!$user->hasRole($role)) {
$roles=$user->getRoles();
array_push($roles,$role);
$user->setRoles($roles);
}
$this->em->persist($user);
$this->em->flush();
}
}

View File

@@ -0,0 +1,53 @@
<?php
namespace App\Command;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Doctrine\ORM\EntityManagerInterface;
use Ratchet\Http\HttpServer;
use Ratchet\Server\IoServer;
use Ratchet\WebSocket\WsServer;
use App\Websocket\MessageHandler;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputOption;
class WebsocketServerCommand extends Command
{
private $container;
private $em;
public function __construct(ContainerInterface $container,EntityManagerInterface $em)
{
parent::__construct();
$this->container = $container;
$this->em = $em;
}
protected function configure()
{
$this
->setName('app:Websocket')
->setDescription('Lauch Websocket server')
->setHelp('Lauch Websocket server')
->addOption('name',null,InputOption::VALUE_REQUIRED,'Websocket server name',null)
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$port = $this->container->getParameter('wssport');
$output->writeln("Starting server on port " . $port);
$server = IoServer::factory(
new HttpServer(
new WsServer(
new MessageHandler($this->container,$this->em)
)
),
$port
);
$server->run();
return 0;
}
}