<?php

namespace Cadoles\CoreBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Form\FormError;
use Ramsey\Uuid\Uuid;
use Ramsey\Uuid\Exception\UnsatisfiedDependencyException;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;

use Cadoles\CoreBundle\Entity\Group;
use Cadoles\CoreBundle\Entity\Usergroup;
use Cadoles\CoreBundle\Entity\Usermodo;
use Cadoles\CoreBundle\Form\GroupType;
use Cadoles\PortalBundle\Entity\Calendar;
use Cadoles\PortalBundle\Entity\Blog;
use Cadoles\PortalBundle\Entity\Project;
use Cadoles\WebsocketBundle\Entity\Message;
use Symfony\Component\Security\Core\User\User;

class GroupController extends Controller
{
    private $labelroute  = 'cadoles_core_config_group';
    private $labelentity = 'CadolesCoreBundle:Group';
    private $labeldata   = 'group';
    private $labeldatas  = 'groups';
    private $idpage;

    public function listAction($access)
    {
      	return $this->render('CadolesCoreBundle:Group:list.html.twig',[
            'useheader'         => true,
            'usemenu'           => false,
            'usesidebar'        => ($access=="config"),
            'access'            => $access
        ]);
    }

    public function ajaxlistAction(Request $request,$access)
    {
        // S'assurer que c'est un appel ajax
        if (!$request->isXmlHttpRequest()) {
            return new JsonResponse(array('message' => 'Interdit'), 400);
        }
        
        $user=$this->getUser();
        $portal_activate=$this->getParameter("portal_activate");

        $em = $this->getDoctrine()->getManager();

        $start=$request->query->get('start');
        $length= $request->query->get('length');
        $search= $request->query->get('search');
        $draw= $request->query->get('draw');
        $order= $request->query->get('order');
      
        // Nombre total d'enregistrement
        $qb=$em->createQueryBuilder();
        $qb->select('COUNT(table)')->from($this->labelentity,'table');
        if($access=="user") {
            $qb->from("CadolesCoreBundle:UserGroup","ug")
               ->andWhere(("table.fgcanshare=:flag"))
               ->andWhere("table.id=ug.group")
               ->andWhere(":user=ug.user")
               ->setParameter("flag", true)
               ->setParameter("user", $user);
            
        }
        $total = $qb->getQuery()->getSingleScalarResult();

        // Nombre d'enregistrement filtré
        if($search["value"]=="")
            $totalf = $total;
        else {
            $qb=$em->createQueryBuilder();
            $qb->select('COUNT(table)')
               ->from($this->labelentity,'table')
               ->leftJoin('CadolesCoreBundle:User', 'u',  'WITH',  'table.owner = u.id')
               ->where('table.label LIKE :value')
               ->orWhere('u.username LIKE :value')
               ->setParameter("value", "%".$search["value"]."%");
            if($access=="user") {
                $qb->from("CadolesCoreBundle:UserGroup","ug")
                   ->andWhere(("table.fgcanshare=:flag"))
                   ->andWhere("table.id=ug.group")
                   ->andWhere(":user=ug.user")
                   ->setParameter("flag", true)
                   ->setParameter("user", $user);
                
            }

            $totalf= $qb->getQuery()->getSingleScalarResult();
        }

        // Construction du tableau de retour
        $output = array(
            'draw' => $draw,
            'recordsFiltered' => $totalf,
            'recordsTotal' => $total,
            'data' => array(),
        );

        // Parcours des Enregistrement
        $qb = $em->createQueryBuilder();
        $qb ->select('table')
            ->from($this->labelentity,'table')
            ->leftJoin('CadolesCoreBundle:User', 'u',  'WITH',  'table.owner = u.id');
        if($access=="user") {
            $qb->from("CadolesCoreBundle:UserGroup","ug")
               ->andWhere(("table.fgcanshare=:flag"))
               ->andWhere("table.id=ug.group")
               ->andWhere(":user=ug.user")
               ->setParameter("flag", true)
               ->setParameter("user", $this->getUser());
            
        }        
        if($search["value"]!="") {
            $qb ->andwhere('table.label LIKE :value')
                ->orWhere('u.username LIKE :value')
                ->setParameter("value", "%".$search["value"]."%");
        }
        switch($order[0]["column"]) {
            case 2 : 
            $qb->orderBy('table.label',$order[0]["dir"]);
            break;
            case 3 : 
            $qb->orderBy('table.fgopen',$order[0]["dir"]);
            break;     
            case 5 : 
            $qb->orderBy('table.fgcanshare',$order[0]["dir"]);
            break;             
            case 6 : 
            $qb->orderBy('table.owner',$order[0]["dir"]);
            break;              
            case 8 : 
            $qb->orderBy('table.fgcancreatepage',$order[0]["dir"]);
            break;                                  
            case 9 : 
            $qb->orderBy('table.fgcancreatecalendar',$order[0]["dir"]);
            break;                                  
            case 10 : 
            $qb->orderBy('table.fgcancreateblog',$order[0]["dir"]);
            break;                                  
            case 11 : 
            $qb->orderBy('table.fgcancreateproject',$order[0]["dir"]);
            break;                                  
        }

        $datas=$qb->setFirstResult($start)->setMaxResults($length)->getQuery()->getResult();

        foreach($datas as $data) {
            $action = "";
            
            if($access=="config") {
                // Modification possible si groupe non template et non tout le monde
                if(!$data->getFgTemplate() && !$data->getFgall())
                    $action .="<a href='".$this->generateUrl('cadoles_core_config_group_update', array('id'=>$data->getId()))."' title='Modifier'><i class='fa fa-file fa-2x fa-fw'></i></a>";
                
                // Modification possible si groupe template mais avec module portail activé
                elseif($data->getFgTemplate()&&$portal_activate)
                    $action .="<a href='".$this->generateUrl('cadoles_core_config_group_update', array('id'=>$data->getId()))."' title='Modifier'><i class='fa fa-file fa-2x fa-fw'></i></a>";
                
                // Modification possible si groupe tout le monde mais avec module portail activé
                elseif($data->getFgall()&&$portal_activate)
                    $action .="<a href='".$this->generateUrl('cadoles_core_config_group_update', array('id'=>$data->getId()))."' title='Modifier'><i class='fa fa-file fa-2x fa-fw'></i></a>";

                if($data->getId()>0&&!$data->getFgall()&&!$data->getFgTemplate()&&$this->isGranted('ROLE_ADMIN')) $action.="<a href='".$this->generateUrl('cadoles_core_config_group_delete', array('id'=>$data->getId()))."' title='Supprimer'><i class='fa fa-trash fa-fw fa-2x'></i></a>";
                if(!$data->getFgall()) $action .="<a href='".$this->generateUrl('cadoles_core_config_group_users', array('id'=>$data->getId()))."' title='Utilisateurs du Groupe'><i class='fa fa-users fa-2x fa-fw'></i></a>";
                
                if($data->getFgcanshare())
                    $action.="<a href='".$this->generateUrl('cadoles_core_'.$access.'_group_statistic', array('id'=>$data->getId()))."' title='Statistique'><i class='fa fa-chart-area fa-fw fa-2x'></i></a>";
            }
            else {
                $fgcanupdate=($user==$data->getOwner());
                $fgcanmanage=false;
                $usergroup=$this->getDoctrine()->getRepository("CadolesCoreBundle:UserGroup")->findOneBy(["user"=>$this->getUser(),"group"=>$data]);
                if($usergroup) $fgcanmanage=($usergroup->getRolegroup()>=90);

                // Modification possible uniquement si l'utilisateur est propriétaire du groupe
                if($fgcanupdate) {
                    $action .="<a href='".$this->generateUrl('cadoles_core_'.$access.'_group_update', array('id'=>$data->getId()))."' title='Modifier'><i class='fa fa-file fa-2x fa-fw'></i></a>";
                    $action .="<a href='".$this->generateUrl('cadoles_core_'.$access.'_group_delete', array('id'=>$data->getId()))."' title='Supprimer'><i class='fa fa-trash fa-2x fa-fw'></i></a>";
                }

                // Gestion des utilisateurs du groupe uniquement pour le proprio ou les managers
                if($fgcanupdate||$fgcanmanage) {
                    $action .="<a href='".$this->generateUrl('cadoles_core_'.$access.'_group_users', array('id'=>$data->getId()))."' title='Utilisateurs du Groupe'><i class='fa fa-users fa-2x fa-fw'></i></a>";
                }
                else {
                    // On ne peut se désinscrire que si le groupe est ouvert et qu'il n'est pas lié à un groupe ldap ou sso
                    $fgcanleave=true;
                    if($data->getFgtemplate() or $data->getFgall()) $fgcanleave=false;
                    elseif(!$data->getFgcanshare() && !$data->getFgopen()) $fgcanleave=false;
                    elseif($data->getFgcanshare() && !$this->get('session')->get('permunsubscribe') && !$data->getFgopen()) $fgcanleave=false;
                    if($fgcanleave) $action.="<a href='".$this->generateUrl('cadoles_core_'.$access.'_group_out', array('id'=>$data->getId()))."' title='Sortir du Groupe'><i class='fa fa-sign-out-alt fa-fw fa-2x'></i></a>";
                }

                if($data->getFgcanshare())
                    $action.="<a href='".$this->generateUrl('cadoles_core_'.$access.'_group_statistic', array('id'=>$data->getId()))."' title='Statistique'><i class='fa fa-chart-area fa-fw fa-2x'></i></a>";
            }
            

            $filtre="";
            if($this->GetParameter("masteridentity")=="LDAP") $filtre=$data->getLdapfilter();
            if($this->GetParameter("masteridentity")=="SSO") $filtre=$data->getAttributes();

            if ($data->getIcon())
                $groupinfo = "<img src='/".$this->container->getParameter('alias')."/".$data->getIcon()->getLabel()."' class='avatar' style='background-color:transparent'/>";
            else
                $groupinfo = "<img src='/".$this->container->getParameter('alias')."/uploads/icon/icon_pin.png' class='avatar' style='background-color:transparent'/>";

            $userinfo="";
            if($data->getOwner()) {
                $userinfo.="<img style='cursor:pointer' onClick='seeUser(".$data->getOwner()->getId().")' src='/".$this->container->getParameter('alias')."/uploads/avatar/".$data->getOwner()->getAvatar()."' class='avatar' style='margin:0px 5px 0px 0px;display:inline-block;'>";
                $userinfo.="<br>".$data->getOwner()->getUsername();
            }

            $visitecpt="";
            $visitelast=null;
            foreach($data->getUsers() as $usergroup) {
                $visitecpt+=$usergroup->getVisitecpt();
                $visitelast=($usergroup->getVisitedate()>$visitelast?$usergroup->getVisitedate():$visitelast);
            }


            array_push($output["data"],array(
                $action,
                $groupinfo,
                $data->getLabel(),
                ($data->getFgopen()?"oui":"non"),
                $filtre,
                ($data->getFgcanshare()?"oui":"non"),
                $userinfo,
                ($visitelast?$visitelast->format("d/m/Y H:i")."<br>":"")."nb = ".$visitecpt,
                ($data->getFgcancreatepage()?"oui":"non"),
                ($data->getFgcancreatecalendar()?"oui":"non"),
                ($data->getFgcancreateblog()?"oui":"non"),
                ($data->getFgcancreateproject()?"oui":"non"),
                )
            );
        }

        // Retour
        return new Response(json_encode($output), 200);
    }    


    public function ajaxusersnotinAction($id,Request $request,$access="config")
    {
        // S'assurer que c'est un appel ajax
        if (!$request->isXmlHttpRequest()) {
            return new JsonResponse(array('message' => 'Interdit'), 400);
        }
        
        $em = $this->getDoctrine()->getManager();
        $group=$this->getData($id);
        $this->canManager($group,$access);

        $sub = $em->createQueryBuilder();
        $sub->select("usergroup");
        $sub->from("CadolesCoreBundle:UserGroup","usergroup");
        $sub->andWhere('usergroup.user = user.id');
        $sub->andWhere('usergroup.group = :groupid');    

        $start=$request->query->get('start');
        $length= $request->query->get('length');
        $search= $request->query->get('search');
        $draw= $request->query->get('draw');
        $order= $request->query->get('order');
      
        // Nombre total d'enregistrement
        $qb = $em->createQueryBuilder();
        if($this->isGranted('ROLE_ADMIN')||$access=="user")
            $qb->select('COUNT(user)')
               ->from('CadolesCoreBundle:User','user')
               ->where($qb->expr()->not($qb->expr()->exists($sub->getDQL())))
               ->setParameter("groupid",$id);
        else {
            $usermodo=$this->get('security.token_storage')->getToken()->getUser()->getId();
            $qb->select('COUNT(user)')
               ->from('CadolesCoreBundle:User','user')
               ->from('CadolesCoreBundle:UserModo','usermodo')
               ->where($qb->expr()->not($qb->expr()->exists($sub->getDQL())))
               ->andWhere("usermodo.niveau01 = user.niveau01")
               ->andWhere("usermodo.user = :userid")
               ->setParameter("userid", $usermodo)
               ->setParameter("groupid",$id);        
        }
        $total=$qb->getQuery()->getSingleScalarResult();

        // Nombre d'enregistrement filtré
        if($search["value"]=="")
            $totalf = $total;
        else {
            if($this->isGranted('ROLE_ADMIN')||$access=="user")
                $totalf= $em->createQueryBuilder()
                            ->select('COUNT(user)')
                            ->from('CadolesCoreBundle:User','user')
                            ->where('user.username LIKE :value OR user.email LIKE :value')
                            ->andWhere($qb->expr()->not($qb->expr()->exists($sub->getDQL())))
                            ->setParameter("value", "%".$search["value"]."%")
                            ->setParameter("groupid",$id)
                            ->getQuery()
                            ->getSingleScalarResult();
            else
                $totalf= $em->createQueryBuilder()
                            ->select('COUNT(user)')
                            ->from('CadolesCoreBundle:User','user')
                            ->from('CadolesCoreBundle:UserModo','usermodo')
                            ->where('user.username LIKE :value OR user.email LIKE :value')
                            ->andWhere($qb->expr()->not($qb->expr()->exists($sub->getDQL())))
                            ->andWhere("usermodo.niveau01 = user.niveau01")
                            ->andWhere("usermodo.user = :userid")
                            ->setParameter("userid", $usermodo)                            
                            ->setParameter("value", "%".$search["value"]."%")
                            ->setParameter("groupid",$id)
                            ->getQuery()
                            ->getSingleScalarResult();
    
        }

        // Construction du tableau de retour
        $output = array(
            'draw' => $draw,
            'recordsFiltered' => $totalf,
            'recordsTotal' => $total,
            'data' => array(),
        );

        // Parcours des Enregistrement
        $qb = $em->createQueryBuilder();
        $qb->select('user')->from("CadolesCoreBundle:User",'user');
        
        if($this->isGranted('ROLE_ADMIN')||$access=="user")
            $qb->where($qb->expr()->not($qb->expr()->exists($sub->getDQL())));
        else 
            $qb->from('CadolesCoreBundle:UserModo','usermodo')
               ->where($qb->expr()->not($qb->expr()->exists($sub->getDQL())))
               ->andWhere("usermodo.niveau01 = user.niveau01")
               ->andWhere("usermodo.user = :userid")
               ->setParameter("userid", $usermodo);                            

        if($search["value"]!="") {
            $qb ->andWhere('user.username LIKE :value OR user.email LIKE :value')
                ->setParameter("value", "%".$search["value"]."%");
        }
        $qb->setParameter("groupid",$id);
        switch($order[0]["column"]) {
            case 2 : 
            $qb->orderBy('user.username',$order[0]["dir"]);
            break;

            case 3 : 
            $qb->orderBy('user.email',$order[0]["dir"]);
            break;
        }

        $datas=$qb->setFirstResult($start)->setMaxResults($length)->getQuery()->getResult();

        foreach($datas as $data) {
            // Action
            $action = "";
            if($group->getLdapfilter()==""&&$group->getAttributes()=="")
                $action.="<a style='cursor:pointer' onClick='addUsers(".$data->getId().")'><i class='fa fa-plus fa-fw'></i></a>";
            
            // Avatar
            $avatar="<img onClick='seeUser(".$data->getId().")' src='/".$this->container->getParameter('alias')."/uploads/avatar/".$data->getAvatar()."' style='width:30px;background-color:#337ab7;margin:auto;display:block;cursor:pointer;'>";

            array_push($output["data"],array("DT_RowId"=>"user".$data->getId(),$action,$avatar,$data->getUsername(),$data->getEmail(),"",""));
        }

        // Retour
        return new Response(json_encode($output), 200);
    }    

    public function ajaxusersinAction($id,Request $request,$access="config")
    {
        // S'assurer que c'est un appel ajax
        if (!$request->isXmlHttpRequest()) {
            return new JsonResponse(array('message' => 'Interdit'), 400);
        }
        
        $em = $this->getDoctrine()->getManager();
        $group=$this->getData($id);
        $this->canManager($group,$access);

        $sub = $em->createQueryBuilder();
        $sub->select("usergroup");
        $sub->from("CadolesCoreBundle:UserGroup","usergroup");
        $sub->andWhere('usergroup.user = user.id');
        $sub->andWhere('usergroup.group = :groupid');    

        $start=$request->query->get('start');
        $length= $request->query->get('length');
        $search= $request->query->get('search');
        $draw= $request->query->get('draw');
        $order= $request->query->get('order');
        $fgcanshare= $request->query->get('fgcanshare');
      
        // Nombre total d'enregistrement
        $qb = $em->createQueryBuilder();
        if($this->isGranted('ROLE_ADMIN')||$access=="user")
            $qb->select('COUNT(user)')
               ->from('CadolesCoreBundle:User','user')
               ->where($qb->expr()->exists($sub->getDQL()))
               ->setParameter("groupid",$id);
        else {
            $usermodo=$this->get('security.token_storage')->getToken()->getUser()->getId();
            $qb->select('COUNT(user)')
               ->from('CadolesCoreBundle:User','user')
               ->from('CadolesCoreBundle:UserModo','usermodo')
               ->where($qb->expr()->exists($sub->getDQL()))
               ->andWhere("usermodo.niveau01 = user.niveau01")
               ->andWhere("usermodo.user = :userid")
               ->setParameter("userid", $usermodo)
               ->setParameter("groupid",$id);        
        }
        $total=$qb->getQuery()->getSingleScalarResult();

        // Nombre d'enregistrement filtré
        if($search["value"]=="")
            $totalf = $total;
        else {
            if($this->isGranted('ROLE_ADMIN')||$access=="user")
                $totalf= $em->createQueryBuilder()
                            ->select('COUNT(user)')
                            ->from('CadolesCoreBundle:User','user')
                            ->where('user.username LIKE :value OR user.email LIKE :value')
                            ->andWhere($qb->expr()->exists($sub->getDQL()))
                            ->setParameter("value", "%".$search["value"]."%")
                            ->setParameter("groupid",$id)
                            ->getQuery()
                            ->getSingleScalarResult();
            else
                $totalf= $em->createQueryBuilder()
                            ->select('COUNT(user)')
                            ->from('CadolesCoreBundle:User','user')
                            ->from('CadolesCoreBundle:UserModo','usermodo')
                            ->where('user.username LIKE :value OR user.email LIKE :value')
                            ->andWhere($qb->expr()->exists($sub->getDQL()))
                            ->andWhere("usermodo.niveau01 = user.niveau01")
                            ->andWhere("usermodo.user = :userid")
                            ->setParameter("userid", $usermodo)                            
                            ->setParameter("value", "%".$search["value"]."%")
                            ->setParameter("groupid",$id)
                            ->getQuery()
                            ->getSingleScalarResult();
    
        }

        // Construction du tableau de retour
        $output = array(
            'draw' => $draw,
            'recordsFiltered' => $totalf,
            'recordsTotal' => $total,
            'data' => array(),
        );

        // Parcours des Enregistrement
        $qb = $em->createQueryBuilder();
        $qb->select('user')->from("CadolesCoreBundle:User",'user');
        
        if($this->isGranted('ROLE_ADMIN')||$access=="user")
            $qb->where($qb->expr()->exists($sub->getDQL()));
        else 
            $qb->from('CadolesCoreBundle:UserModo','usermodo')
               ->where($qb->expr()->exists($sub->getDQL()))
               ->andWhere("usermodo.niveau01 = user.niveau01")
               ->andWhere("usermodo.user = :userid")
               ->setParameter("userid", $usermodo);                            

        if($search["value"]!="") {
            $qb ->andWhere('user.username LIKE :value OR user.email LIKE :value')
                ->setParameter("value", "%".$search["value"]."%");
        }
        $qb->setParameter("groupid",$id);
        switch($order[0]["column"]) {
            case 2 : 
                $qb->orderBy('user.username',$order[0]["dir"]);
            break;

            case 3 : 
                $qb->orderBy('user.email',$order[0]["dir"]);
            break;
        }

        $datas=$qb->setFirstResult($start)->setMaxResults($length)->getQuery()->getResult();
        $user=$this->getUser();

        $config=$em->getRepository('CadolesCoreBundle:Config')->find("datausers");
        $fields=$config->getValue();
        $fields=json_decode($fields,true);
        if(!is_array($fields)) $fields=[];
        if(!array_key_exists("visite",$fields)) $fields["visite"]["perm"]=0;
        $fgviewvisite=($fields["visite"]["perm"]==1);
                
        foreach($datas as $data) {
            // Propriétaire
            $usergroup=$em->getRepository("CadolesCoreBundle:UserGroup")->findOneBy(["user"=>$data->getId(),"group"=>$id]);
            $fgproprio=($usergroup->getUser()==$group->getOwner());

            // Action
            $action = "";
            if($group->getLdapfilter()==""&&$group->getAttributes()==""&&!$fgproprio)
                $action.="<a style='cursor:pointer' onClick='delUsers(".$data->getId().")'><i class='fa fa-minus fa-fw'></i></a>";

            // Avatar
            $avatar="<img onClick='seeUser(".$data->getId().")' src='/".$this->container->getParameter('alias')."/uploads/avatar/".$data->getAvatar()."' style='width:30px;background-color:#337ab7;margin:auto;display:block;cursor:pointer'>";
            
            // Flag manager
            $rolegroup="";
            if($fgcanshare) {
                if($fgproprio) $rolegroup="Propriétaire du groupe";
                elseif($user==$usergroup->getUser()) $rolegroup="Gestionnaire";
                else {
                    $selectuser=($usergroup->getRolegroup()==0?"selected='selected'":"");
                    $selectwritter=($usergroup->getRolegroup()==50?"selected='selected'":"");
                    $selectmanager=($usergroup->getRolegroup()==90?"selected='selected'":"");

                    $rolegroup='<select id="roleuser-'.$data->getId().'" name="user[visible]" onChange="changeRole('.$data->getId().');"><option value="0" '.$selectuser.'>Utilisateur</option><option value="50" '.$selectwritter.'>Collaborateur</option><option value="90" '.$selectmanager.'>Gestionnaire</option></select>';
                }
            }
        
            // Visite
            if($fgviewvisite) {
                $visite="";
                if($usergroup->getVisitedate()) {
                    $visite=$usergroup->getVisitedate()->format("d/m/Y H:i")."<br>nb = ".$usergroup->getVisitecpt();
                }
            }
            if($fgviewvisite)
                $tmp=array("DT_RowId"=>"user".$data->getId(),$action,$avatar,$data->getUsername(),$data->getEmail(),$visite,$rolegroup);
            else
                $tmp=array("DT_RowId"=>"user".$data->getId(),$action,$avatar,$data->getUsername(),$data->getEmail(),$rolegroup);

            array_push($output["data"],$tmp);
        }

        // Retour
        return new Response(json_encode($output), 200);
    } 

    public function usergroupaddAction(Request $request,$access="config")
    {
        // S'assurer que c'est un appel ajax
        if (!$request->isXmlHttpRequest()) {
            return new JsonResponse(array('message' => 'Interdit'), 400);
        }

        $em = $this->getDoctrine()->getManager();

        $output=array();
        $userid=$request->request->get('userid');
        $groupid=$request->request->get('groupid');

        $group=$em->getRepository("CadolesCoreBundle:Group")->find($groupid);
        $this->canManager($group,$access);
        if($group->getFgAll()||$group->getFgtemplate())
            throw $this->createNotFoundException('Permission denied');

        $usergroup = $em->getRepository("CadolesCoreBundle:Usergroup")->findOneBy(array("user"=>$userid,"group"=>$groupid));
        if($usergroup) {
            $response = new Response(json_encode($output));    
            $response->headers->set('Content-Type', 'application/json');        
            return $response;
        }

        $key = Uuid::uuid4();
        $usergroup=new UserGroup();
        $user=$em->getRepository("CadolesCoreBundle:User")->find($userid);
        $usergroup->setUser($user);
        $usergroup->setGroup($group);
        $usergroup->setKeyvalue($key);
        $usergroup->setRolegroup(0);
        $em->persist($usergroup);
        $em->flush();

        // Notification message
        $user=$em->getRepository("CadolesCoreBundle:User")->find($userid);
        $message="Inscription de l'utilisateur<br>".$user->getLastname()." ".$user->getFirstname()."<br>Par ".$this->getUser()->getLastname()." ".$this->getUser()->getFirstname();
        $websocket = $this->container->get('cadoles.websocket.pushmessage')->send($key->toString(),$userid,$groupid,$message);

        // Notification mail auprès de la personne inscrite
        if($group->getFgcanshare()&&$this->get('session')->get('fgnotifgroup')) {
            $idpage =$group->getPages()->first()->getId();
            $url = $this->generateUrl('cadoles_core_redirect', ["route"=>"cadoles_core_home","id"=>$idpage], UrlGeneratorInterface::ABSOLUTE_URL);
            $texthtml="Vous venez d'être inscrit dans le groupe de travail : ".$group->getLabel()."<br>Suivez le lien suivant pour y accéder = <a href='$url'>$url</a>";
            $text="Vous venez d'être inscrit dans le groupe de travail : ".$group->getLabel()."<br>Suivez le lien suivant pour y accéder = $url";

            $template="template";
            $mail_params=array(
                "subject" => $this->get('session')->get('appname')." : Inscription au groupe de travail : ".$group->getLabel()."\n\n".$group->getDescription(),
                "body_html"=>$texthtml,
                "body_text"=>$text
            );
            $to = $user->getEmail();
            $from =  $this->getParameter('noreply');
            $fromName = $this->get('session')->get('appname');
            $message = $this->container->get('cadoles.core.service.mail');
            $message->sendEmail($template, $mail_params, $to, $from, $fromName);        
        }

        // Retour
        $response = new Response(json_encode($output));    
        $response->headers->set('Content-Type', 'application/json');        
        return $response;
    }

    public function usergroupdelAction(Request $request,$access="config")
    {
        // S'assurer que c'est un appel ajax
        if (!$request->isXmlHttpRequest()) {
            return new JsonResponse(array('message' => 'Interdit'), 400);
        }
       
        $em = $this->getDoctrine()->getManager();

        $output=array();
        $userid=$request->request->get('userid');
        $groupid=$request->request->get('groupid');
        
        $group=$em->getRepository("CadolesCoreBundle:Group")->find($groupid);
        $this->canManager($group,$access);
        if($group->getFgAll()||$group->getFgTemplate())
            throw $this->createNotFoundException('Permission denied');

        // Notification message
        $data = $em->getRepository("CadolesCoreBundle:Usergroup")->findOneBy(array("user"=>$userid,"group"=>$groupid));
        $user=$em->getRepository("CadolesCoreBundle:User")->find($userid);
        $message="Désinscription de l'utilisateur<br>".$user->getLastname()." ".$user->getFirstname()."<br>Par ".$this->getUser()->getLastname()." ".$this->getUser()->getFirstname();;
        $websocket = $this->container->get('cadoles.websocket.pushmessage')->send($data->getKeyvalue(),$userid,$groupid,$message);

        // Desinscription
        $em->remove($data);
        $em->flush();

        // Notification mail auprès des managers
        if($group->getFgcanshare()&&$this->get('session')->get('fgnotifgroup')) {
            $text=$user->getUsername()." a été désinscrit du groupe de travail : ".$group->getLabel();
            $template="template";
            $mail_params=array(
                "subject" => $this->get('session')->get('appname')." : ".$user->getUsername()." = Désinscription au groupe de travail ".$group->getLabel()."\n\n".$group->getDescription(),
                "body_html"=>nl2br($text),
                "body_text"=>$text
            );
            $usergroups=$em->getRepository("CadolesCoreBundle:Usergroup")->findBy(array("group"=>$groupid));
            $to=array();
            foreach($usergroups as $usergroup) {
                if($usergroup->getRolegroup()>=90)
                    array_push($to,$usergroup->getUser()->getEmail());
            }

            $from =  $this->getParameter('noreply');;
            $fromName = $this->get('session')->get('appname');
            $message = $this->container->get('cadoles.core.service.mail');
            $message->sendEmail($template, $mail_params, $to, $from, $fromName);        
        }
                
        $response = new Response(json_encode($output));    
        $response->headers->set('Content-Type', 'application/json');        
        return $response;
    }

    public function outAction(Request $request,$id,$access="config")
    {
        $em = $this->getDoctrine()->getManager();
        $group=$em->getRepository("CadolesCoreBundle:Group")->find($id);
        if($group->getFgAll()||$group->getFgTemplate())
            throw $this->createNotFoundException('Permission denied');

        // Notification message
        $usergroup = $em->getRepository("CadolesCoreBundle:Usergroup")->findOneBy(array("user"=>$this->getUser(),"group"=>$id));
        if($usergroup) {
            $user=$em->getRepository("CadolesCoreBundle:User")->find($this->getUser());
            $message="Désinscription de l'utilisateur<br>".$user->getLastname()." ".$user->getFirstname()."<br>Par ".$this->getUser()->getLastname()." ".$this->getUser()->getFirstname();;
            $websocket = $this->container->get('cadoles.websocket.pushmessage')->send($usergroup->getKeyvalue(),$this->getUser()->getId(),$id,$message);
        }

        // Desinscription
        $em->remove($usergroup);
        $em->flush();

        // Notification mail auprès des managers
        if($group->getFgcanshare()&&$this->get('session')->get('fgnotifgroup')) {
            $text=$user->getUsername()." a été désinscrit du groupe de travail : ".$group->getLabel();
            $template="template";
            $mail_params=array(
                "subject" => $this->get('session')->get('appname')." : ".$user->getUsername()." = Désinscription au groupe de travail ".$group->getLabel()."\n\n".$group->getDescription(),
                "body_html"=>nl2br($text),
                "body_text"=>$text
            );
            $usergroups=$em->getRepository("CadolesCoreBundle:Usergroup")->findBy(array("group"=>$group));
            $to=array();
            foreach($usergroups as $usergroup) {
                if($usergroup->getRolegroup()>=90)
                    array_push($to,$usergroup->getUser()->getEmail());
            }

            $from =  $this->getParameter('noreply');;
            $fromName = $this->get('session')->get('appname');
            $message = $this->container->get('cadoles.core.service.mail');
            $message->sendEmail($template, $mail_params, $to, $from, $fromName);        
        }



        return $this->redirect($this->generateUrl("cadoles_core_user_group"));
    }

    public function changeroleAction(Request $request,$access="config")
    {
        // S'assurer que c'est un appel ajax
        if (!$request->isXmlHttpRequest()) {
            return new JsonResponse(array('message' => 'Interdit'), 400);
        }
        
        $em = $this->getDoctrine()->getManager();

        $output=array();
        $userid=$request->request->get('user');
        $groupid=$request->request->get('group');
        $role=$request->request->get('role');

        $group=$em->getRepository("CadolesCoreBundle:Group")->find($groupid);
        $this->canManager($group,$access);

        $data = $em->getRepository("CadolesCoreBundle:Usergroup")->findOneBy(array("user"=>$userid,"group"=>$groupid));
        if($data) $data->setRolegroup($role);

        $em->persist($data);
        $em->flush();

        $response = new Response(json_encode($output));    
        $response->headers->set('Content-Type', 'application/json');        
        return $response;
    }

    public function submitAction(Request $request, $access="config")
    {
        $em = $this->getDoctrine()->getManager();

        // Permission
        if($access=="user") {
            $permgroup=$this->get('session')->get('permgroup');
            if($permgroup=="NO_BODY") throw $this->createNotFoundException('Permission denied');
            if($permgroup=="ROLE_ANIM" && $this->isGranted('ROLE_USER')) throw $this->createNotFoundException('Permission denied');
            if($permgroup=="ROLE_MODO" && ($this->isGranted('ROLE_ANIM') || $this->isGranted('ROLE_USER'))) throw $this->createNotFoundException('Permission denied');
        }

        // Initialisation de l'enregistrement
        $data = new Group();
        $data->setFgopen(false);
        $data->setFgcanshare(($access=="user"));
        $data->setFgcancreatepage(false);
        $data->setFgcancreatecalendar(false);
        $data->setFgcancreateblog(false);
        $data->setFgcancreateproject(false);
        if($access=="user") {
            $data->setOwner($this->getUser());
            if($this->getParameter("portal_activate")) {
                $template=$em->getRepository("CadolesPortalBundle:Page")->findoneby(["parentfor"=>"group"]);
                $data->setPagetemplate($template);
            }
        }

        // Création du formulaire
        $form = $this->createForm(GroupType::class,$data,array(
            "mode"=>"submit",
            "fgall"=>false,
            "updatelimite"=>false,
            "access"=>$access,
            "masteridentity"=> $this->GetParameter("masteridentity"),
            "portal_activate"=>$this->getParameter("portal_activate")
            )
        );

        // Récupération des data du formulaire
        $form->handleRequest($request);
        
        // Sur erreur
        $this->getErrorForm(null,$form,$request,$data,"submit",$access);
        
        // Sur validation
        if ($form->get('submit')->isClicked() && $form->isValid()) {  
            $data = $form->getData();  
            $data->setFgall(false);
            $data->setFgtemplate(false);
            if($data->getLdapfilter()!="") $data->setFgopen(false);
            if($data->getAttributes()!="") $data->setFgopen(false);
            if($access=="user") $data->setOwner($this->getUser());

            // Icon
            $idicon = $form->get('idicon')->getData();
            $icon=$em->getRepository("CadolesPortalBundle:Icon")->findoneby(["id"=>$idicon]);
            $data->setIcon($icon);   
            
            // Sauvegarde
            $em->persist($data);
            $em->flush();

            // On s'assure que le propriétaire est bien membre du groupe
            $this->ctrlOwner($data);

            // On s'assure que le groupe de travail à bien page d'accueil / calendrier / blog associé
            // Sinon on les génère
            $this->ctrlFgcanshare($data,$access);

            // Retour à la liste
            return $this->redirectToRoute("cadoles_core_".$access."_group_users",["id"=>$data->getId(),"idreturn"=>$this->idpage]);
        }
        
        // Affichage du formulaire
        $icons=$this->getDoctrine()->getRepository("CadolesPortalBundle:Icon")->findBy(["user"=>null]);
        $iconsuser=null;
        if($access=="user") $iconsuser=$this->getDoctrine()->getRepository("CadolesPortalBundle:Icon")->findBy(["user"=>$this->getUser()]);

        return $this->render($this->labelentity.':edit.html.twig', [
            'useheader'         => true,
            'usemenu'           => false,
            'usesidebar'        => ($access=="config"),              
            $this->labeldata    => $data,
            'mode'              => 'submit',
            'access'            => $access,
            'icons'             => $icons,
            'iconsuser'         => $iconsuser,            
            'form'              => $form->createView()
        ]);
    }  

    public function updateAction($id,Request $request,$access="config")
    {
        // Récupération de l'enregistrement courant 
        $em = $this->getDoctrine()->getManager();
        $data=$this->getData($id);
        $oldowner=$data->getOwner();

        $this->canOwner($data,$access);

        // Création du formulaire
        $form = $this->createForm(GroupType::class,$data,array(
            "mode"              => "update",
            "access"            => $access,
            "fgall"             => $data->getFgAll(),
            "updatelimite"      => ($data->getFgAll()||$data->getFgTemplate()),
            "masteridentity"    => $this->GetParameter("masteridentity"),
            "portal_activate"   => $this->getParameter("portal_activate"),
            "idicon"            => ($data->getIcon()?$data->getIcon()->getId():null),
            )
        );

        // Récupération des data du formulaire
        $form->handleRequest($request);
    
        // Sur erreur
        $this->getErrorForm($id,$form,$request,$data,"update",$access);
        
        // Sur validation
        if ($form->get('submit')->isClicked() && $form->isValid()) {
            $data = $form->getData();

            $masteridentity=$this->GetParameter("masteridentity");
            if($masteridentity!="LDAP") $data->setLdapfilter(null);
            if($masteridentity!="SSO") $data->setAttributes(null);
            if($data->getLdapfilter()!="") $data->setFgopen(false);
            if($data->getAttributes()!="") $data->setFgopen(false);
            
            // Icon
            $idicon = $form->get('idicon')->getData();
            $icon=$this->getDoctrine()->getRepository("CadolesPortalBundle:Icon")->findoneby(["id"=>$idicon]);
            $data->setIcon($icon); 
            
            // Sauvegarde
            $em->persist($data);
            $em->flush();

            // On s'assure que le propriétaire est bien membre du groupe
            $this->ctrlOwner($data);

            // On s'assure que le groupe de travail à bien page d'accueil / calendrier / blog associé
            // Sinon on les génère
            $this->ctrlFgcanshare($data,$access);

            // Si le propriétaire change de main on prévient le nouveau propriétaire
            if($data->getOwner()&&$data->getOwner()!=$oldowner&&$this->get('session')->get('fgnotifgroup')) {
                // Email à destination de l'inscript pour le prévenir qu'un administrateur doit valider
                $text="On vient de vous tranférer la propriété du groupe ".$data->getLabel();
                $template="template";
                $mail_params=array(
                    "subject" =>  $this->get('session')->get('appname')." : Transfert de groupe",
                    "body_html"=>nl2br($text),
                    "body_text"=>$text
                );
                $to = $data->getOwner()->getEmail();
                $from =  $this->getParameter('noreply');
                $fromName = $this->get('session')->get('appname');
                $message = $this->container->get('cadoles.core.service.mail');
                $message->sendEmail($template, $mail_params, $to, $from, $fromName);
            }

            // Retour à la liste
            return $this->redirectToRoute("cadoles_core_".$access."_group");
        }
        
        $icons=$em->getRepository("CadolesPortalBundle:Icon")->findBy(["user"=>null]);
        $iconsuser=null;
        if($access=="user") $iconsuser=$em->getRepository("CadolesPortalBundle:Icon")->findBy(["user"=>$this->getUser()]);

        // Affichage du formulaire
        return $this->render($this->labelentity.':edit.html.twig', [
            'useheader'         => true,
            'usemenu'           => false,
            'usesidebar'        => ($access=="config"),            
            $this->labeldata    => $data,
            'mode'              => 'update',
            'access'            => $access,
            'icons'             => $icons,
            'iconsuser'         => $iconsuser,            
            'form'              => $form->createView()
        ]);
    }

    public function deleteAction($id,Request $request, $access="config")
    {
        $em = $this->getDoctrine()->getManager();

        // Seule role admin peut supprimer un groupe
        if($access=="config"&&!$this->isGranted('ROLE_ADMIN'))
            return $this->redirectToRoute($this->labelroute);

        // Récupération de l'enregistrement courant 
        $data=$this->getData($id);
        $this->canOwner($data,$access);

        // Vérifier que cet enregistrement est supprimable
        if($data->getFgAll()||$data->getFgTemplate())
            throw $this->createNotFoundException('Permission denied');

        // Création du formulaire
        $form = $this->createForm(GroupType::class,$data,array(
            "mode"=>"delete",
            "updatelimite"=>($data->getFgAll()||$data->getFgTemplate()),
            "masteridentity"=> $this->GetParameter("masteridentity"),
            "portal_activate"=>$this->getParameter("portal_activate")
            )
        );

        // Récupération des data du formulaire
        $form->handleRequest($request);        

        // Sur erreur
        $this->getErrorForm($id,$form,$request,$data,"delete",$access);
                
        // Sur validation
        if ($form->get('submit')->isClicked() && $form->isValid()) {
            // Si le groupe est un groupe de travail
            if($data->getFgcanshare()) {
                // Sur l'ensemble des pages liés
                $pages=$data->getPages();
                foreach($pages as $page) {
                    $groups=$page->getGroups();
                    // si la page est lié qu'à un seul group on peut la supprimer
                    if($groups->count()==1)
                        $em->remove($page);
                }

                // Sur l'ensemble des calendar liés
                $calendars=$data->getCalendars();
                foreach($calendars as $calendar) {
                    $groups=$calendar->getGroups();
                    // si la page est lié qu'à un seul group on peut la supprimer
                    if($groups->count()==1)
                        $em->remove($calendar);
                }                

                // Sur l'ensemble des blog liés
                $blogs=$data->getBlogs();
                foreach($blogs as $blog) {
                    $groups=$blog->getGroups();
                    // si la page est lié qu'à un seul group on peut la supprimer
                    if($groups->count()==1)
                        $em->remove($blog);
                }  
                
                // Sur l'ensemble des project liés
                $projects=$data->getProjects();
                foreach($projects as $project) {
                    $groups=$project->getGroups();
                    // si la page est lié qu'à un seul group on peut la supprimer
                    if($groups->count()==1)
                        $em->remove($project);
                }                  
            }

            $em->remove($data);
            $em->flush();
            
            return $this->redirectToRoute("cadoles_core_".$access."_group");
        }
        
        $icons=$em->getRepository("CadolesPortalBundle:Icon")->findBy(["user"=>null]);
        $iconsuser=null;
        if($access=="user") $iconsuser=$em->getRepository("CadolesPortalBundle:Icon")->findBy(["user"=>$this->getUser()]);

        // Affichage du formulaire
        return $this->render($this->labelentity.':edit.html.twig', [
            'useheader'         => true,
            'usemenu'           => false,
            'usesidebar'        => ($access=="config"),   
            $this->labeldata    => $data,
            'mode'              => 'delete',
            'access'            => $access,
            'icons'             => $icons,
            'iconsuser'         => $iconsuser,               
            'form'              => $form->createView()
        ]);                    
    }

    public function usersAction($id,Request $request, $access="config")
    {      
        // Récupération de l'enregistrement courant 
        $data=$this->getData($id);
        $this->canManager($data,$access);

        // idreturn ?
        $idreturn=$request->get("idreturn");

        $em = $this->getDoctrine()->getManager();
        $config=$em->getRepository('CadolesCoreBundle:Config')->find("datausers");
        $fields=$config->getValue();
        $fields=json_decode($fields,true);
        if(!is_array($fields)) $fields=[];
        if(!array_key_exists("visite",$fields)) $fields["visite"]["perm"]=0;
        $fgviewvisite=($fields["visite"]["perm"]==1);
        
        // Affichage du formulaire
        return $this->render($this->labelentity.':users.html.twig', [
            'useheader'         => true,
            'usemenu'           => false,
            'usesidebar'        => ($access=="config"),               
            'access'            => $access,
            $this->labeldata    => $data,
            'idreturn'          => $idreturn,
            'fgviewvisite'      => $fgviewvisite,
        ]);  
    }

    public function groupexportAction(Request $request, $access="config")
    {      
        $em = $this->getDoctrine()->getManager();
        $dir    = $this->get('kernel')->getRootDir() . '/../uploads/export/';
        $file   = "exportgroup.csv";

        $fs = new Filesystem();
        $fs->mkdir($dir);

        $csvh = fopen($dir.$file, 'w');
        $d = ';'; // this is the default but i like to be explicit
        $e = '"'; // this is the default but i like to be explicit

        // Entête de colonne     
        $data=["id","Label","Ouvert","Groupe de Travail","Propriétaire","Date Visite","Cpt Visite","Création Page","Création Calendriers","Création Blogs","Création Projets"];
        fputcsv($csvh, $data, $d, $e);

        // Liste des utilisateurs en fonction du role de l'utilisateur en cours
        $groups=$em->getRepository("CadolesCoreBundle:Group")->findAll();
        
        foreach($groups as $group) {
            $data = [
                "id"=>$group->getId(),
                "label"=>$group->getLabel(),
                "fgopen"=>($group->getFgopen()?"oui":"non"),
                "fgcanshare"=>($group->getFgcanshare()?"oui":"non"),
                "owner"=>($group->getOwner()?$group->getOwner()->getUsername():""),
                "visitedate"=>"",
                "visitecpt"=>"",
                "fgcancreatepage"=>($group->getFgcancreatepage()?"oui":"non"),
                "fgcancreatecalendar"=>($group->getFgcancreatecalendar()?"oui":"non"),
                "fgcancreateblog"=>($group->getFgcancreateblog()?"oui":"non"),
                "fgcancreateproject"=>($group->getFgcancreateproject()?"oui":"non"),
            ];

            $visitecpt="";
            $visitelast=null;
            foreach($group->getUsers() as $usergroup) {
                $visitecpt+=$usergroup->getVisitecpt();
                $visitelast=($usergroup->getVisitedate()>$visitelast?$usergroup->getVisitedate():$visitelast);
            }
            
            $data["visitedate"]=($visitelast?$visitelast->format("d/m/Y H:i"):"");
            $data["visitecpt"]=$visitecpt;

            fputcsv($csvh, $data, $d, $e);
        }
        fclose($csvh);        

        $response = new BinaryFileResponse($dir.$file);
        $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT);
        
        return $response; 
    }

    public function usergroupexportAction($id,Request $request, $access="config")
    {      
        // Récupération de l'enregistrement courant 
        $group=$this->getData($id);
        $this->canManager($group,$access);

        $em = $this->getDoctrine()->getManager();
        $dir    = $this->get('kernel')->getRootDir() . '/../uploads/export/';
        $file   = "export-".$id.".csv";

        $fs = new Filesystem();
        $fs->mkdir($dir);

        $csvh = fopen($dir.$file, 'w');
        $d = ';'; // this is the default but i like to be explicit
        $e = '"'; // this is the default but i like to be explicit

        // Entête de colonne     
        $data=["id","Login","Nom","Prénom","Email","Téléphone",$this->getParameter("labelniveau01"),$this->getParameter("labelniveau02"),"Métier","Fonction","Nom Usage","Autres Prénom","Sexe","Adresse","Date Naissance","Pays Naissance","Ville Naissance","Date Visite","Nb Visites"];
        fputcsv($csvh, $data, $d, $e);

        // Liste des utilisateurs en fonction du role de l'utilisateur en cours
        $qb = $em->createQueryBuilder();
        if($this->isGranted('ROLE_ADMIN')||$access=="user") {
            $users = $qb->select('user')
                    ->from('CadolesCoreBundle:User','user')
                    ->from('CadolesCoreBundle:UserGroup','usergroup')
                    ->where('usergroup.group=:group')
                    ->andWhere('usergroup.user=user')
                    ->setParameter("group", $id)
                    ->getQuery()
                    ->getResult();
        }
        elseif($this->isGranted('ROLE_MODO')) {
            $users = $qb->select('user')
                    ->from('CadolesCoreBundle:User','user')
                    ->from('CadolesCoreBundle:UserGroup','usergroup')
                    ->from('CadolesCoreBundle:Niveau01','niveau01')
                    ->from('CadolesCoreBundle:UserModo', 'usermodo')                    
                    ->where('usergroup.group=:group')
                    ->andWhere('usergroup.user=user')
                    ->andwhere('user.niveau01=niveau01.id')
                    ->andwhere("usermodo.niveau01 = user.niveau01")
                    ->andWhere("usermodo.user = :userid")                    
                    ->setParameter("group", $id)
                    ->setParameter("userid", $this->getUser()->getId())
                    ->getQuery()
                    ->getResult();
        }        
        
        foreach($users as $user) {
            $data = [
                "id"=>$user->getId(),
                "username"=>$user->getUsername(),
                "name"=>$user->getLastname(),
                "firstname"=>$user->getFirstname(),
                "email"=>$user->getEmail(),
                "phone"=>$user->getTelephonenumber(),
                "niveau01"=>$user->getNiveau01()->getLabel(),
                "niveau02"=>($user->getNiveau02()?$user->getNiveau02()->getLabel():""),
                "job"=>$user->getJob(),
                "position"=>$user->getPosition(),
                "usualname"=>$user->getUsualname(),
                "givensname"=>$user->getGivensname(),
                "gender"=>$user->getGender(),
                "postaladress"=>$user->getPostaladress(),
                "birthdate"=>($user->getBirthdate()?$user->getBirthdate()->format("d/m/Y"):""),
                "birthcountry"=>($user->getBirthcountry()?$user->getBirthcountry()->getLabel():""),
                "birthplace"=>($user->getBirthplace()?$user->getBirthplace()->getLabel():""),
                "visitedate"=>"",
                "visitecpt"=>"",
            ];

            $usergroup=$em->getRepository("CadolesCoreBundle:UserGroup")->findOneBy(["user"=>$user,"group"=>$group]);
            if($usergroup) {
                if($usergroup->getVisitedate()) {
                    $data["visitedate"]=$usergroup->getVisitedate()->format("d/m/Y H:i");
                    $data["visitecpt"]=$usergroup->getVisitecpt();
                }
            }

            fputcsv($csvh, $data, $d, $e);
        }
        fclose($csvh);        

        $response = new BinaryFileResponse($dir.$file);
        $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT);
        
        return $response; 
    }

    public function statisticAction($id,$access) {
        $group=$this->getData($id);
        $em = $this->getDoctrine()->getManager();
        if(!$group) throw $this->createNotFoundException('Permission denied');
    
        if($access!="config") {
            $usergroup=$em->getRepository("CadolesCoreBundle:UserGroup")->findOneBy(["user"=>$this->getUser(),"group"=>$group]);
            if(!$usergroup) throw $this->createNotFoundException('Permission denied');
        }
        
        $groupcptvisite=$em->getRepository("CadolesCoreBundle:Statistic")->findOneBy(["keyvalue"=>"groupcptvisite","group"=>$group]);
        $groupcptmessage=$em->getRepository("CadolesCoreBundle:Statistic")->findOneBy(["keyvalue"=>"groupcptmessage","group"=>$group]);
        $groupcptblogarticle=$em->getRepository("CadolesCoreBundle:Statistic")->findOneBy(["keyvalue"=>"groupcptblogarticle","group"=>$group]);
        $groupcptprojecttask=$em->getRepository("CadolesCoreBundle:Statistic")->findOneBy(["keyvalue"=>"groupcptprojecttask","group"=>$group]);


        return $this->render('CadolesCoreBundle:Group:statistic.html.twig',[
            'useheader'             => true,
            'usemenu'               => false,
            'usesidebar'            => ($access=="config"),
            'access'                => $access,   
            'group'                 => $group,
            'groupcptvisite'        => $groupcptvisite,
            'groupcptmessage'       => $groupcptmessage,
            'groupcptblogarticle'   => $groupcptblogarticle,
            'groupcptprojecttask'   => $groupcptprojecttask,
    
        ]);
    }

    public function invitationAction($id,Request $request, $access="config")
    {      
        // Récupération de l'enregistrement courant 
        $em = $this->getDoctrine()->getManager();
        $group=$this->getData($id);
        $this->canManager($group,$access);

        $invitations=$group->getInvitations();
        if(!is_array($invitations)) $invitations=[];

        foreach($invitations as $key => $mail) {
            $user=$em->getRepository("CadolesCoreBundle:User")->findOneBy(["email"=>$mail]);
            // Si l'utilisateur est inscript plus la peine de le suivre
            if($user) {
                $listinvitations[$key]=["email"=>$mail,"statut"=>"","relance"=>false];
                $usergroup=$em->getRepository("CadolesCoreBundle:UserGroup")->findOneBy(["user"=>$user,"group"=>$group]);
                if($usergroup)
                    $listinvitations[$key]["statut"]="Inscrit dans le groupe";
                else
                    $listinvitations[$key]["statut"]="Inscrit sur ".$this->get('session')->get('appname')." mais pas dans le groupe";
            }
            else {
                $listinvitations[$key]=["email"=>$mail,"statut"=>"Non inscrit sur ".$this->get('session')->get('appname'),"relance"=>true];
                $user=$em->getRepository("CadolesCoreBundle:Registration")->findOneBy(["email"=>$mail]);
                if($user) {
                    $listinvitations[$key]["statut"]=$user->getStatut()->getLabel();
                    $listinvitations[$key]["relance"]=false;
                }
            }
        }

        return $this->render('CadolesCoreBundle:Group:invitations.html.twig',[
            'useheader'     => false,
            'usemenu'       => false,
            'usesidebar'    => false,
            'id'            => $id,
            'invitations'   => $listinvitations,
        ]);          
    }

    protected function canManager($group,$access) {
        if($access!="config") {
            $em = $this->getDoctrine()->getManager();
            $user=$em->getRepository("CadolesCoreBundle:Usergroup")->findOneBy(["group"=>$group,"user"=>$this->getUser()]);
            if(!$user||$user->getRolegroup()<90) 
                throw $this->createNotFoundException('Permission denied');
        }
    }

    protected function canOwner($group,$access) {
        if($access!="config") {
            $em = $this->getDoctrine()->getManager();
            $isowner=($group->getOwner()==$this->getUser());
            if(!$isowner) 
                throw $this->createNotFoundException('Permission denied');
        }
    }    

    protected function ctrlOwner($group) {
        $em = $this->getDoctrine()->getManager();
        // Le propriétaire passe manager
        $usergroups=$em->getRepository("CadolesCoreBundle:Usergroup")->findBy(["group"=>$group,"rolegroup"=>"100"]);
        foreach($usergroups as $usergroup) {
            $usergroup->setRolegroup(90);
            $em->persist($usergroup);
            $em->flush();                
        }

        // Le propriétaire prend son role dans le groupe
        if($group->getOwner()) {
            $usergroup=$em->getRepository("CadolesCoreBundle:Usergroup")->findOneBy(["group"=>$group,"user"=>$group->getOwner()]);
            if(!$usergroup) {
                $key = Uuid::uuid4();
                $usergroup=new UserGroup();
                $usergroup->setUser($group->getOwner());
                $usergroup->setGroup($group);
                $usergroup->setKeyvalue($key);
            }
            $usergroup->setRolegroup(100);
            $em->persist($usergroup);
            $em->flush();                
        }
    }

    protected function ctrlFgcanshare($group,$access) {
        $em = $this->getDoctrine()->getManager();

        if($group->getFgcanshare()) {
            // On regarde s'il a au moins une page
            if($group->getPages()->isEmpty()) {
                $page=$this->getDoctrine()->getRepository("CadolesPortalBundle:Page")->clonePage(null,$group->getPagetemplate());
                $group->addPage($page);
                $page->setName($group->getLabel());
                if($access=="user")$page->setUser($this->getUser());

                $em->persist($page);
                $em->persist($group);
                $em->flush();
                
            }
            $pages=$group->getPages();
            $this->idpage=$pages[0]->getId();
            if($pages[0]->getName()!=$group->getLabel()) {
                $pages[0]->setName($group->getLabel());
                $em->persist($pages[0]);
                $em->flush();
            }
            foreach($pages as $page) {
                $page->setUser($group->getOwner());
                $em->persist($page);
                $em->flush();                
            }

            // On regarde s'il a au moins un calendrier
            if($group->getCalendars()->isEmpty()) {
                $calendar=new Calendar();
                $key = Uuid::uuid4();

                $calendar->setName($group->getLabel());
                $calendar->setKeyvalue($key);                
                $calendar->addGroup($group);
                $calendar->setColor($group->getColor());
                $calendar->setType(0);
                if($access=="user")$calendar->setUser($this->getUser());

                $em->persist($calendar);
                $em->flush();                  
            }
            else {
                $calendars=$group->getCalendars();
                if($calendars[0]->getName()!=$group->getLabel()) {
                    $calendars[0]->setName($group->getLabel());
                    $em->persist($calendars[0]);
                    $em->flush();
                }
                foreach($calendars as $calendar) {
                    $calendar->setUser($group->getOwner());
                    $em->persist($calendar);
                    $em->flush();                
                }                
            }

            // On regarde s'il a au moins un blog
            if($group->getBlogs()->isEmpty()) {
                $blog=new Blog();

                $blog->setName($group->getLabel());
                $blog->addGroup($group);
                if($access=="user")$blog->setUser($this->getUser());

                $em->persist($blog);
                $em->flush();                  
            }
            else {            
                $blogs=$group->getBlogs();
                if($blogs[0]->getName()!=$group->getLabel()) {
                    $blogs[0]->setName($group->getLabel());
                    $em->persist($blogs[0]);
                    $em->flush();
                }
                foreach($blogs as $blog) {
                    $blog->setUser($group->getOwner());
                    $em->persist($blog);
                    $em->flush();                
                }                
            }

            // On regarde s'il a au moins un project
            if($group->getProjects()->isEmpty()) {
                $project=new Project();

                $project->setName($group->getLabel());
                $project->addGroup($group);
                if($access=="user")$project->setUser($this->getUser());

                $em->persist($project);
                $em->flush();                  
            }
            else {            
                $projects=$group->getProjects();
                if($projects[0]->getName()!=$group->getLabel()) {
                    $projects[0]->setName($group->getLabel());
                    $em->persist($projects[0]);
                    $em->flush();
                }
                foreach($projects as $project) {
                    $project->setUser($group->getOwner());
                    $em->persist($project);
                    $em->flush();                
                }                  
            }
        }
    }


    protected function getDatas()
    {
        $em = $this->getDoctrine()->getManager();
        $datas = $em->getRepository($this->labelentity)->findAll();
        return $datas;
    } 
            
    protected function getData($id)
    {
        $em = $this->getDoctrine()->getManager();
        $data = $em->getRepository($this->labelentity)->find($id);

        if (!$data) {
            throw $this->createNotFoundException('Unable to find '.$this->labeldata);
        }

        return $data;
    } 

    protected function getEntityBy($entity,$key,$value)
    {
        $em = $this->getDoctrine()->getManager();
        $datas = $em->createQueryBuilder()
                      ->select('u')
                      ->from($entity,  'u')
                      ->where('u.'.$key.'=:value')
                      ->getQuery()->setParameter("value", $value)
                      ->getResult();
        if (!$datas) return false;
        else return true;
    }

    protected function getErrorForm($id,$form,$request,$data,$mode,$access) {
        if ($form->get('submit')->isClicked()&&$mode=="delete") {
        
        }

        if ($form->get('submit')->isClicked() && ($mode=="submit" || $mode=="update")) {
            $tmp=$this->getEntityBy("CadolesCoreBundle:Niveau01","label",$data->getLabel());
            if($tmp) $form->addError(new FormError('Un niveau de rang 01 utilise déjà ce label'));

            $tmp=$this->getEntityBy("CadolesCoreBundle:Niveau02","label",$data->getLabel());
            if($tmp) $form->addError(new FormError('Un niveau de rang 02 utilise déjà ce label'));

            // On s'assure que le label ne contient pas des caractères speciaux
            $string = preg_replace('~[^ éèêôöàïî\'@a-zA-Z0-9._-]~', '', $data->getLabel());
            if($string!=$data->getLabel())
            {
                $form->addError(new FormError('Caractères interdit dans ce label'));
            } 

            if($data->getFgcanshare()&&is_null($data->getPagetemplate()))
                $form->addError(new FormError("Un groupe de travail doit avoir un modèle de page d'accueil"));
        }

        if ($form->get('submit')->isClicked() && $mode=="update" && $access=="user") {
            if(!$data->getOwner()) $form->addError(new FormError('Le propriétaire du groupe est obligatoire'));
        }

        if ($form->get('submit')->isClicked() && !$form->isValid()) {
            $this->get('session')->getFlashBag()->clear();
            $validator = $this->get('validator');
            $errors = $validator->validate($data);
            foreach( $errors as $error ) {
                $request->getSession()->getFlashBag()->add("error", $error->getMessage());
            }

            $errors = $form->getErrors();
            foreach( $errors as $error ) {
                $request->getSession()->getFlashBag()->add("error", $error->getMessage());
            }
        }
    }    
}
