ninegate/src/ninegate-1.0/src/Cadoles/CoreBundle/Command/SynchroCommand.php

692 lines
32 KiB
PHP

<?php
namespace Cadoles\CoreBundle\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\Finder\Finder;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpKernel\KernelInterface;
use Doctrine\DBAL\Connection as DBALConnection;
use Doctrine\ORM\EntityManager;
use Cadoles\CoreBundle\Entity\Niveau01;
use Cadoles\CoreBundle\Entity\Niveau02;
use Cadoles\CoreBundle\Entity\User;
use Cadoles\CoreBundle\Entity\Group;
use Cadoles\CoreBundle\Entity\UserGroup;
global $bdd01;
global $config;
class SynchroCommand extends Command
{
private $container;
private $em;
private $output;
private $filesystem;
private $rootlog;
protected function configure()
{
$this
->setName('Core:Synchro')
->setDescription('Synchronisation Annuaire')
->setHelp('This command Synchro for Core')
->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->container = $this->getApplication()->getKernel()->getContainer();
$this->em = $this->container->get('doctrine')->getEntityManager();
$this->output = $output;
$this->filesystem = new Filesystem();
$this->rootlog = $this->container->get('kernel')->getRootDir()."/../var/logs/";
$this->writelnred('');
$this->writelnred('== Core:Synchro');
$this->writelnred('==========================================================================================================');
setlocale( LC_CTYPE, 'fr_FR' );
$labelniveau01 = mb_strtoupper($this->container->getParameter('labelniveau01'));
$labelniveau02 = mb_strtoupper($this->container->getParameter('labelniveau02'));
$masteridentity = $this->container->getParameter('masteridentity');
$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');
$this->writeln('');
$this->writeln('=====================================================');
$this->writeln('== SYNCHONISATION ANNUAIRE ==========================');
$this->writeln('=====================================================');
$ldap = $this->container->get('cadoles.core.service.ldap');
if(!$ldap->isEnabled()) {
if($masteridentity =="LDAP") {
$this->writeln('');
$this->writeln('=====================================================');
$this->writeln('== SYNCHONISATION LDAP TO BUNDLE ====================');
$this->writeln('=====================================================');
$ldap_basedn = $this->container->getParameter('ldap_basedn');
$ldap_template = $this->container->getParameter('ldap_template');
$ldap_username = $this->container->getParameter('ldap_username');
$ldap_firstname = $this->container->getParameter('ldap_firstname');
$ldap_lastname = $this->container->getParameter('ldap_lastname');
$ldap_email = $this->container->getParameter('ldap_email');
$ldap_usersadmin = $this->container->getParameter('ldap_usersadmin');
$fieldstoread = array($ldap_username,$ldap_firstname,$ldap_lastname,$ldap_email);
$ldapusers = array();
if($ldap_template=="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);
$this->writeln('');
$this->writeln('== CLASSES ==========================================');
$results = $ldap->search("type=Classe", ['cn','description','gidNumber'], $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);
}
}
$this->writeln('');
$this->writeln('== USERS ============================================');
// On parcours les niveaux 01 pour connaitre les filtres ldap associé
$datas=$this->em->createQueryBuilder()->select('table')->from('CadolesCoreBundle:Niveau01','table')->where('table.ldapfilter IS NOT NULL')->getQuery()->getResult();
foreach($datas as $data) {
// On execute le filtre d'appartenance à ce niveau
$results = $ldap->search($data->getLdapfilter(), $fieldstoread, $ldap_basedn);
// Pour chaque utilisateur ldap
foreach($results as $result) {
// On sauvegarde ce user
array_push($ldapusers,$result[$ldap_username]);
// Création ou Modification du user
$user=$this->em->getRepository('CadolesCoreBundle:User')->findBy(array('username' => $result[$ldap_username]));
if(!$user) {
$this->writeln(" - Création dans Bundle >> ".$result[$ldap_username]);
if(!$simulate) $this->addUser($data,$result[$ldap_username],$result[$ldap_firstname],$result[$ldap_lastname],$result[$ldap_email],$ldap_usersadmin);
}
else {
$this->writeln(" - Modification dans Bundle >> ".$result[$ldap_username]);
if(!$simulate) $this->modUser($user[0],$result[$ldap_username],$result[$ldap_firstname],$result[$ldap_lastname],$result[$ldap_email],$ldap_usersadmin);
}
}
}
$this->writeln('');
$this->writeln('== USERS GROUP ======================================');
$groups=$this->em->getRepository('CadolesCoreBundle:Group')->findAll();
foreach($groups as $group) {
$ldapusersgroup=array();
$ldapfilter=$group->getLdapfilter();
$this->writeln('');
$this->writeln('== '.$group->getLabel());
if(!is_null($ldapfilter)) {
$results = $ldap->search($ldapfilter,[$ldap_username,"memberuid"] , $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('CadolesCoreBundle: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('CadolesCoreBundle: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('CadolesCoreBundle: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);
}
}
}
$members=$this->em->getRepository('CadolesCoreBundle:UserGroup')->findBy(array('group' => $group));
foreach($members as $member) {
if(!in_array($member->getUser()->getUsername(),$ldapusersgroup)) {
$this->writeln(" - Détattacher >> ".$member->getUser()->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('CadolesCoreBundle:User')->findAll();
foreach($users as $user) {
// Si l'utilisateur n'est pas dans la liste des users ldap : on le supprime
if(!in_array($user->getUsername(),$ldapusers)) {
$this->writeln(" - Suppression dans Bundle >> ".$user->getUsername());
if(!$simulate) {
$this->em->remove($user);
$this->em->flush();
}
}
}
}
}
else {
$this->writeln('');
$this->writeln('=====================================================');
$this->writeln('== SYNCHONISATION BUNDLE TO LDAP ====================');
$this->writeln('=====================================================');
$this->writeln('');
$this->writeln('== NIVEAU01 =========================================');
$baseNiveau01 = $this->container->getParameter('ldap_baseniveau01');
$datas = $this->em
->createQueryBuilder()
->select('table')
->from('CadolesCoreBundle:Niveau01','table')
->getQuery()
->getResult();
foreach($datas as $data) {
$criteria = '(cn='.$data->getLabel().')';
$subbranch=$baseNiveau01;
$results = $ldap->search($criteria, array('cn'), $subbranch);
// Mise à jour si elle existe
if(count($results) > 0) {
$this->writeln(' - Modification dans annuaire >> '.$data->getLabel());
if(!$simulate) $ldap->modifyNiveau01($data,$data->getLabel());
}
// Sinon création de la fiche
else {
$this->writeln(' - Création dans annuaire >> '.$data->getLabel());
if(!$simulate) $ldap->addNiveau01($data);
}
}
$this->writeln('');
$this->writeln('== NIVEAU02 =========================================');
$baseNiveau02 = $this->container->getParameter('ldap_baseniveau02');
$datas = $this->em
->createQueryBuilder()
->select('table')
->from('CadolesCoreBundle:Niveau02','table')
->getQuery()
->getResult();
foreach($datas as $data) {
$criteria = '(cn='.$data->getLabel().')';
$subbranch=$baseNiveau02;
$results = $ldap->search($criteria, array('cn'), $subbranch);
// Mise à jour si elle existe
if(count($results) > 0) {
$this->writeln(' - Modification dans annuaire >> '.$data->getLabel());
if(!$simulate) $ldap->modifyNiveau02($data,$data->getLabel());
}
// Sinon création de la fiche
else {
$this->writeln(' - Création dans annuaire >> '.$data->getLabel());
if(!$simulate) $ldap->addNiveau02($data);
}
}
$this->writeln('');
$this->writeln('== GROUP ============================================');
$baseGroup = $this->container->getParameter('ldap_basegroup');
$datas = $this->em
->createQueryBuilder()
->select('table')
->from('CadolesCoreBundle:Group','table')
->getQuery()
->getResult();
foreach($datas as $data) {
$criteria = '(cn='.$data->getLabel().')';
$subbranch=$baseGroup;
$results = $ldap->search($criteria, array('cn'), $subbranch);
// Mise à jour si elle existe
if(count($results) > 0) {
$this->writeln(' - Modification dans annuaire >> '.$data->getLabel());
if(!$simulate) $ldap->modifyGroup($data,$data->getLabel());
}
// Sinon création de la fiche
else {
$this->writeln(' - Création dans annuaire >> '.$data->getLabel());
if(!$simulate) $ldap->addGroup($data);
}
}
$this->writeln('');
$this->writeln('== USER =============================================');
$baseUser = $this->container->getParameter('ldap_baseuser');
$datas = $this->em
->createQueryBuilder()
->select('table')
->from('CadolesCoreBundle:User','table')
->getQuery()
->getResult();
foreach($datas as $data) {
$criteria = '(uid='.$data->getUsername().')';
$subbranch=$baseUser;
$results = $ldap->search($criteria, array('uid'), $subbranch);
// S'assurer que SIREN correspond au Niveau01
if($data->getNiveau01()->getSiren()!=$data->getSiren()) {
$data->SetSiren($data->getNiveau01()->getSiren());
$data->flush();
}
// S'assurer que SIRET correspond au Niveau02
if($data->getNiveau02()!==null&&$data->getNiveau01()->getSiren()!=$data->getSiren()) {
$data->SetSiret($data->getNiveau02()->getSiret());
$data->flush();
}
// Mise à jour si elle existe
if(count($results) > 0) {
$this->writeln(' - Modification dans annuaire >> '.$data->getUsername());
if(!$simulate) $ldap->modifyUser($data);
}
// Sinon création de la fiche
else {
$this->writeln(' - Création dans annuaire >> '.$data->getUsername());
if(!$simulate) $ldap->addUser($data);
}
// Rattachement à Niveau01 et Niveau02
if(!$simulate) $ldap->addGroupUser($data);
}
$this->writeln('');
$this->writeln('== USER GROUP =======================================');
$baseGroup = $this->container->getParameter('ldap_basegroup');
$datas = $this->em
->createQueryBuilder()
->select('table')
->from('CadolesCoreBundle:Group','table')
->getQuery()
->getResult();
foreach($datas as $data) {
$criteria = '(cn='.$data->getLabel().')';
$subbranch=$baseGroup;
$results = $ldap->search($criteria, array('cn'), $subbranch);
// Mise à jour des membres du groupes
if(count($results) > 0) {
$this->writeln(' - '.$data->getLabel());
$dn=$ldap->getGroupDN($data->getLabel());
$attrs["memberuid"]=array();
$attrs["cadolesMember"]=array();
foreach($data->getUsers() as $usergroupe) {
array_push($attrs["memberuid"],$usergroupe->getUser()->getUsername());
array_push($attrs["cadolesMember"],$ldap->getUserDN($usergroupe->getUser()));
$this->writeln(' > '.$usergroupe->getUser()->getUsername());
}
if(!$simulate) $ldap->ldapModify($dn, $attrs);
}
}
$this->writeln('');
$this->writeln('=====================================================');
$this->writeln('== SYNCHONISATION LDAP TO BUNDLE ====================');
$this->writeln('=====================================================');
$this->writeln('');
$this->writeln('== NIVEAU01 =========================================');
$baseNiveau01 = $this->container->getParameter('ldap_baseniveau01');
$criteria = '(cn=*)';
$subbranch=$baseNiveau01;
$results = $ldap->search($criteria, array('cn'), $subbranch);
foreach($results as $result) {
$data = $this->em->getRepository('CadolesCoreBundle:Niveau01')->findBy(array('label' => $result["cn"]));
if($data) $this->writeln(' - Existe dans bundle >> '.$result["cn"]);
else {
$this->writeln(' - A supprimer dans annuaire >> '.$result["cn"]);
$dn=$ldap->getNiveau01DN($result["cn"]);
if(!$simulate) $ldap->deleteByDN($dn);
}
}
$this->writeln('');
$this->writeln('== NIVEAU02 =========================================');
$baseNiveau02 = $this->container->getParameter('ldap_baseniveau02');
$criteria = '(cn=*)';
$subbranch=$baseNiveau02;
$results = $ldap->search($criteria, array('cn'), $subbranch);
foreach($results as $result) {
$data = $this->em->getRepository('CadolesCoreBundle:Niveau02')->findBy(array('label' => $result["cn"]));
if($data) $this->writeln(' - Existe dans bundle >> '.$result["cn"]);
else {
$this->writeln(' - A supprimer dans annuaire >> '.$result["cn"]);
$dn=$ldap->getNiveau02DN($result["cn"]);
if(!$simulate) $ldap->deleteByDN($dn);
}
}
$this->writeln('');
$this->writeln('== GROUP ============================================');
$baseGroup = $this->container->getParameter('ldap_basegroup');
$criteria = '(cn=*)';
$subbranch=$baseGroup;
$results = $ldap->search($criteria, array('cn'), $subbranch);
foreach($results as $result) {
$data = $this->em->getRepository('CadolesCoreBundle:Group')->findBy(array('label' => $result["cn"]));
if($data) $this->writeln(' - Existe dans bundle >> '.$result["cn"]);
else {
$this->writeln(' - A supprimer dans annuaire >> '.$result["cn"]);
$dn=$ldap->getGroupDN($result["cn"]);
if(!$simulate) $ldap->deleteByDN($dn);
}
}
$this->writeln('');
$this->writeln('== USER =============================================');
$baseUser = $this->container->getParameter('ldap_baseuser');
$criteria = '(uid=*)';
$subbranch=$baseUser;
$results = $ldap->search($criteria, array('uid'), $subbranch);
foreach($results as $result) {
$data = $this->em->getRepository('CadolesCoreBundle:User')->findBy(array('username' => $result["uid"]));
if($data) $this->writeln(' - Existe dans bundle >> '.$result["uid"]);
else {
$this->writeln(' - A supprimer dans annuaire >> '.$result["uid"]);
$dn='uid='.$result["uid"].','.$baseUser;
if(!$simulate) $ldap->deleteByDN($dn);
}
}
}
$eportail = $this->container->get('cadoles.core.service.eportail');
if($eportail->isEnabled()) {
$this->writeln('');
$this->writeln('=====================================================');
$this->writeln('== SYNCHONISATION BUNDLE TO EPORTAIL ================');
$this->writeln('=====================================================');
$this->writeln('');
$this->writeln('== NIVEAU01 =========================================');
$datas = $this->em
->createQueryBuilder()
->select('table')
->from('CadolesCoreBundle:Niveau01','table')
->getQuery()
->getResult();
foreach($datas as $data) {
$this->writeln(' - Synchronisation eportail >> '.$data->getLabel());
if(!$simulate) $eportail->syncNiveau01($data,$data->getLabel());
}
$this->writeln('');
$this->writeln('== NIVEAU02 =========================================');
$datas = $this->em
->createQueryBuilder()
->select('table')
->from('CadolesCoreBundle:Niveau02','table')
->getQuery()
->getResult();
foreach($datas as $data) {
$this->writeln(' - Synchronisation eportail >> '.$data->getLabel());
if(!$simulate) $eportail->syncNiveau02($data,$data->getLabel());
}
$this->writeln('');
$this->writeln('== GROUP ============================================');
$datas = $this->em
->createQueryBuilder()
->select('table')
->from('CadolesCoreBundle:Group','table')
->getQuery()
->getResult();
foreach($datas as $data) {
$this->writeln(' - Synchronisation eportail >> '.$data->getLabel());
if(!$simulate) $eportail->syncGroup($data,$data->getLabel());
}
$this->writeln('');
$this->writeln('== USER =============================================');
$datas = $this->em
->createQueryBuilder()
->select('table')
->from('CadolesCoreBundle:User','table')
->getQuery()
->getResult();
foreach($datas as $data) {
$this->writeln(' - Synchronisation eportail >> '.$data->getUsername());
if(!$simulate) $eportail->syncUser($data);
}
$this->writeln('');
$this->writeln('=====================================================');
$this->writeln('== SYNCHONISATION EPORTAIL TO BUNDLE ================');
$this->writeln('=====================================================');
$dbeportail= $this->container->get('service_container')->get('doctrine.orm.eportail_entity_manager')->getConnection();
$this->writeln('');
$this->writeln('== GROUP ============================================');
$sql = "SELECT * FROM env_group WHERE group_id>0";
$query = $dbeportail->prepare($sql);
$query->execute();
while($row=$query->fetch()){
$fgOK=false;
if (strpos($row["group_name"], $labelniveau01.' = ') === 0) {
$tmp=str_replace("$labelniveau01 = ","",$row["group_name"]);
$data = $this->em->getRepository('CadolesCoreBundle:Niveau01')->findBy(array('label' =>$tmp));
if($data) {
$fgOK=true;
$this->writeln(' - Existe dans bundle >> '.$row["group_name"]);
}
}
if (strpos($row["group_name"], $labelniveau02.' = ') === 0) {
$tmp=str_replace("$labelniveau01 = ","",$row["group_name"]);
$data = $this->em->getRepository('CadolesCoreBundle:Niveau02')->findBy(array('label' =>$tmp));
if($data) {
$fgOK=true;
$this->writeln(' - Existe dans bundle >> '.$row["group_name"]);
}
}
if (strpos($row["group_name"], 'GROUPE = ') === 0) {
$tmp=str_replace("GROUPE = ","",$row["group_name"]);
$data = $this->em->getRepository('CadolesCoreBundle:Group')->findBy(array('label' =>$tmp));
if($data) {
$fgOK=true;
$this->writeln(' - Existe dans bundle >> '.$row["group_name"]);
}
}
if(!$fgOK) {
$this->writeln(' - A supprimer dans eportail >> '.$row["group_name"]);
if(!$simulate) delGroup($row["group_id"]);
}
}
$this->writeln('');
$this->writeln('== USER =============================================');
$sql = "SELECT * FROM env_user WHERE user_id>0";
$query = $dbeportail->prepare($sql);
$query->execute();
while($row=$query->fetch()){
$data = $this->em->getRepository('CadolesCoreBundle:User')->findBy(array('username' =>$row["user_login"]));
if($data) $this->writeln(' - Existe dans bundle >> '.$row["user_login"]);
else {
$this->writeln(' - A supprimer dans eportail >> '.$row["user_login"]);
if(!$simulate) delUser($row["user_id"]);
}
}
}
$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");
}
protected function addmodGroup($label,$ldapfilter,$fgcanshare) {
$group=$this->em->getRepository('CadolesCoreBundle:Group')->findOneBy(array('fgtemplate' => true, 'label' => $label));
if(!$group) {
$group=new Group();
$group->setFgcanshare($fgcanshare);
}
$group->setLabel($label);
$group->setFgopen(false);
$group->setFgall(false);
$group->setLdapfilter($ldapfilter);
$group->setFgtemplate(true);
$this->em->persist($group);
$this->em->flush();
}
protected function addtoGroup($user,$group) {
$member=$this->em->getRepository('CadolesCoreBundle:UserGroup')->findOneBy(array('group' => $group, 'user' => $user));
if(!$member) {
$member= new UserGroup();
$member->setGroup($group);
$member->setUser($user);
$this->em->persist($member);
$this->em->flush();
}
}
protected function addUser($niveau01,$username,$firstname,$lastname,$email,$usersadmin) {
$user = new User();
$user->setUsername($username);
$user->setLastname($lastname);
$user->setFirstname($firstname);
$user->setEmail($email);
$user->setNiveau01($niveau01);
$user->setSiren($niveau01->getSiren());
$user->setPassword("PASSWORDFROMEXTERNE");
$user->setVisible(true);
$user->setAuthlevel("simple");
$user->setBelongingpopulation("agent");
if(in_array($username,$usersadmin))
$user->setRole("ROLE_ADMIN");
else
$user->setRole("ROLE_USER");
$this->em->persist($user);
$this->em->flush();
}
protected function modUser($user,$username,$firstname,$lastname,$email,$usersadmin) {
$user->setLastname($lastname);
$user->setFirstname($firstname);
$user->setEmail($email);
if(in_array($username,$usersadmin))
$user->setRole("ROLE_ADMIN");
$this->em->persist($user);
$this->em->flush();
}
}