<?php

namespace Cadoles\PortalBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpFoundation\File\File;
use GuzzleHttp\Exception\RequestException;
use Symfony\Component\Form\FormError;


use Cadoles\PortalBundle\Entity\Pagewidget;
use Cadoles\PortalBundle\Form\PagewidgetType;

class PagewidgetController extends Controller
{
    private $labelentity="CadolesPortalBundle:Pagewidget";
    private $routeprimary="cadoles_portal_config_pagewidget";

    private $entity;
    private $page;
    private $id;
    private $access;
    private $look;
    private $mini;
    private $selwidget;   
    private $usage;   
    private $group;
    
    private $cansee;
    private $canupdate;
    private $canadd;

    private function searchArray($array, $key, $value) { 
        $results = array(); 
    
        if (is_array($array)) 
        { 
            if (isset($array[$key]) && $array[$key] == $value) 
                $results[] = $array; 
    
            foreach ($array as $subarray) 
                $results = array_merge($results, $this->searchArray($subarray, $key, $value)); 
        } 
    
        return $results; 
    } 

    private function entityForm(Pagewidget $entity,$idpage,$id,$access="config",$by="view") {
        if ($this->getDoctrine()->getManager()->contains($entity)) {
            $widgettype= $this->getDoctrine()->getManager()->getRepository("CadolesPortalBundle:Pagewidget")->find($id)->getWidget();
            $params = $widgettype->getParameter();
            $values = $entity->getParameter();

            foreach($params->fields as $key => $param) {
                $tmp = $this->searchArray($values,"id",$param->id);
                if(is_array($tmp)&&!empty($tmp)) 
                    $params->fields[$key]->value=$tmp[0]["value"];
                else
                    $params->fields[$key]->value=$param->value;
            }

            return $this->createForm(PagewidgetType::class, $entity, [
                'param'     => $params,
                'mode'      => "update",
                'access'    => $access,
                'idicon'    => ($entity->getIcon()?$entity->getIcon()->getId():$widgettype->getIcon()->getId()),
                'method'    => 'POST',
            ]);
        } else {
            $widgettype= $this->getDoctrine()->getManager()->getRepository("CadolesPortalBundle:Widget")->find($id);
            $entity->setName($widgettype->getName());
            $entity->setHeight($widgettype->getHeight());
            $entity->setAutoajust($widgettype->getAutoajust());
            $entity->setBorder($widgettype->getBorder());
            $entity->setColorheaderback($widgettype->getColorheaderback());
            $entity->setColorheaderfont($widgettype->getColorheaderfont());
            $entity->setColorbodyback($widgettype->getColorbodyback());
            $entity->setColorbodyfont($widgettype->getColorbodyfont());
            $entity->setIcon($widgettype->getIcon());

            $param = $widgettype->getParameter();
            return $this->createForm(PagewidgetType::class, $entity, [
                'param'     => $param,
                'mode'      => ($by=="view"?"submit":"submittemplate"),
                'access'    => $access,
                'idicon'    => $widgettype->getIcon()->getId(),
                'method'    => 'POST',
            ]);
        }
    }

    public function submitAction(Request $request,$idpage,$idwidgettype,$access="config") {
        $by=$request->query->get('by');
        $entity = new Pagewidget();
        $form   = $this->entityForm($entity,$idpage,$idwidgettype,$access,$by);
        $form->handleRequest($request);
        

        // On s'assure que la page où l'on souhaite insérer un widget est bien du bon type
        $page=$this->getDoctrine()->getRepository("CadolesPortalBundle:Page")->findoneby(["id"=>$idpage]);
        if (!$page)
            throw $this->createNotFoundException('Unable to find entity.');
        if($page->getPagecategory()->getId()!=2)
            throw $this->createNotFoundException('Permission denied');

        // Sur erreur
        $this->getErrorForm(null,$form,$request,$idwidgettype,$page,$entity,"submit");
        
        // Sur validation
        if ($form->get('submit')->isClicked() && $form->isValid()) {  
            $idicon = $form->get('idicon')->getData();
            $icon=$this->getDoctrine()->getRepository("CadolesPortalBundle:Icon")->findoneby(["id"=>$idicon]);
            $widgettype=$this->getDoctrine()->getRepository("CadolesPortalBundle:Widget")->findoneby(["id"=>$idwidgettype]);

            // Localisation par défaut en R1C1
            $entity->setLoc("R1C1");
            $entity->setRoworder("1");

            // Rattachement icon / panel / widgettype
            $entity->setIcon($icon);
            $entity->setPage($page);
            $entity->setWidget($widgettype);

            // Récupération des paramétres
            $jsons=$widgettype->getParameter();
            $param=array();
            $param["fields"]=array();
            foreach($jsons->fields as $field) {
                $tmp=array();
                $tmp["id"]=$field->id;
                $tmp["value"]=($field->type!="hidden"?$form->get($field->id)->getData():"");
                array_push($param["fields"],$tmp);
            }

            $entity->setParameter($param);

            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            
            // Notification création widget
            $groups=$page->getGroups();
            if($groups[0]) {
                if($groups[0]->getFgcanshare()) {
                    $message="Création Widget ".$entity->getName();
                    $usergroup=$em->getRepository("CadolesCoreBundle:Usergroup")->findOneBy(["group"=>$groups[0],"user"=>$this->getUser()]);
                    if($usergroup) {
                        $key=$usergroup->getKeyvalue();
                        $websocket = $this->container->get('cadoles.websocket.pushmessage')->send($key,$this->getUser()->getId(),$groups[0]->getId(),$message);                    
                    }
                }
            }

            if($access=="config") {
                if($by=="view")
                    return $this->redirect($this->generateUrl('cadoles_portal_config_page_view',["id"=>$idpage]));
                else
                    return $this->redirect($this->generateUrl('cadoles_portal_config_pagetemplate_view',["id"=>$idpage]));
            }
            else
                return $this->redirect($this->generateUrl('cadoles_core_home',["id"=>$idpage]));
        }

        $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"),
            'maxwidth'          => ($access=="user"),                     
            'entity'            => $entity,
            'icons'             => $icons,
            'iconsuser'         => $iconsuser,
            'mode'              => ($by=="view"?"submit":"submittemplate"),
            'access'            => $access,
            'idpage'            => $idpage,
            'form'              => $form->createView(),
        ]);
    }

    public function updateAction(Request $request,$idpage,$idwidget,$access="config") {
        $by=$request->query->get('by');
        $usage=$request->query->get('usage');
        $group=$request->query->get('group');

        // Recherche du pagewidget
        $em = $this->getDoctrine()->getManager();
        $entity = $em->getRepository($this->labelentity)->find($idwidget);
        if (!$entity) throw $this->createNotFoundException('Unable to find entity.');

        // On s'assure que l'utilisateur à la permission de modifier
        if($access=="user") {
            $em->getRepository("CadolesPortalBundle:Page")->getPermission($this->getUser(),$entity->getPage(),$cansee,$canupdate,$canadd);
            if(!$canupdate) throw $this->createNotFoundException('Permission denied');
        }

        // Création du formulaire
        $form   = $this->entityForm($entity,$idpage,$idwidget,$access,$by);
        $form->handleRequest($request);

        // Validation
        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();

            $idicon = $form->get('idicon')->getData();
            $icon=$this->getDoctrine()->getRepository("CadolesPortalBundle:Icon")->findoneby(["id"=>$idicon]);
            $entity->setIcon($icon);
            
            // Récupération des paramétres
            $widgettype= $entity->getWidget();
            $jsons=$widgettype->getParameter();
            $param=array();
            $param["fields"]=array();
            foreach($jsons->fields as $field) {
                $tmp=array();
                $tmp["id"]=$field->id;

                $tmp["value"]=($field->type!="hidden"?$form->get($field->id)->getData():"");
                array_push($param["fields"],$tmp);
            }

            $entity->setParameter($param);
            
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            // Si widget RSS On supprime le potentiel cache de ce flux
            if($entity->getWidget()->getId()==-1880) {
                $dir = $this->container->getParameter('kernel.root_dir').'/../web/uploads/flux/';
                $mask = $dir."widget-".$entity->getId().".*";
                array_map( "unlink", glob( $mask ) );
            }

            // Retour
            if($by=="view")
                return $this->redirect($this->generateUrl('cadoles_portal_'.$access.'_page_view',["id"=>$idpage,"usage"=>$usage,"group"=>$group]));
            else
                return $this->redirect($this->generateUrl('cadoles_portal_'.$access.'_pagetemplate_view',["id"=>$idpage]));
        }

        $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'         => ($access=="config"),
            'usemenu'           => false,
            'usesidebar'        => ($access=="config"),   
            'maxwidth'          => ($access=="user"),                  
            'entity'            => $entity,
            'icons'             => $icons,
            'iconsuser'         => $iconsuser,            
            'mode'              => ($by=="view"?"update":"updatetemplate"),
            'access'            => $access,   
            'idpage'            => $idpage,         
            'form'              => $form->createView(),
            'usage'             => $usage,
            'group'             => $group
        ]);
    }

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

        // Récupération des parametres
        $output=array();
        $idwidget=$request->request->get('idwidget');

        // Recherche du pagetwidget
        $em = $this->getDoctrine()->getManager();
        $entity = $em->getRepository($this->labelentity)->find($idwidget);
        if (!$entity) throw $this->createNotFoundException('Unable to find entity.');

        // On s'assure que l'utilisateur à la permission de supprimer
        if($access=="user") {
            $em->getRepository("CadolesPortalBundle:Page")->getPermission($this->getUser(),$entity->getPage(),$cansee,$canupdate,$canadd);
            if(!$canupdate) throw $this->createNotFoundException('Permission denied');
        }

        // Notification création widget
        $groups=$entity->getPage()->getGroups();
        if($groups[0]) {
            if($groups[0]->getFgcanshare()) {
                $message="Suppression Widget ".$entity->getName();
                $usergroup=$em->getRepository("CadolesCoreBundle:Usergroup")->findOneBy(["group"=>$groups[0],"user"=>$this->getUser()]);
                if($usergroup) {
                    $key=$usergroup->getKeyvalue();
                    $websocket = $this->container->get('cadoles.websocket.pushmessage')->send($key,$this->getUser()->getId(),$groups[0]->getId(),$message);                    
                }
            }
        }

        // Supression du pagewidget
        $em->remove($entity);
        $em->flush();

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

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

        $output=array();
        $idwidget=$request->request->get('idwidget');
        $order=$request->request->get('order');
        $idloc=$request->request->get('idloc');

        $em = $this->getDoctrine()->getManager();
        $entity = $em->getRepository($this->labelentity)->find($idwidget);
        if (!$entity) {
            throw $this->createNotFoundException('Unable to find entity.');
        }

        $entity->setRoworder($order);
        $entity->setLoc($idloc);
        $em->persist($entity);
        $em->flush();

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

    public function uploadAction(Request $request,$access=null) {
        // Fichier temporaire uploadé
        $tmpfile    = $request->files->get('upload');
        $extention  = $tmpfile->getClientOriginalExtension();

        // Répertoire de Destination
        $fs         = new Filesystem();
        $rootdir    = $this->get('kernel')->getRootDir()."/../web";
        $fs->mkdir($rootdir."/uploads/ckeditor");
        
        // Fichier cible
        $targetName = uniqid().".".$extention;
        $targetFile = $rootdir."/uploads/ckeditor/".$targetName;
        $targetUrl  = "/".$this->getParameter('alias')."/uploads/ckeditor/".$targetName;
        $message    = "";

        move_uploaded_file($tmpfile,$targetFile);
        
        $output["uploaded"]=1;
        $output["fileName"]=$targetName;
        $output["url"]=$targetUrl;

        return new Response(json_encode($output));

    }

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

        if ($form->get('submit')->isClicked() && ($mode=="submit" || $mode=="update")) {
            // Interdire l'insertion de 2 chat dans la meme page
            if($idwidgettype==-1840) {
                $pagewidget=$this->getDoctrine()->getRepository("CadolesPortalBundle:Pagewidget")->findoneby(["page"=>$page,"widget"=>-1840]);
                if($pagewidget) {
                    $form->addError(new FormError("Vous ne pouvez pas insérer deux widgets de type Chat dans la même page"));
                }
            }
        }

        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());
            }
        }
    }

    protected function setRequest($request,$id,$access) {
        $this->em           = $this->getDoctrine()->getManager();
        $this->user         = $this->getUser();       
        $this->id           = $id;
        $this->access       = $access;
        $this->look         = $request->query->get('look');   
        $this->selwidget    = $request->query->get('selwidget');   
        $this->usage        = $request->query->get('usage');
        $this->group        = $request->query->get('group');
        
        // Le widget existe-t-il ?
        $this->entity = $this->em->getRepository($this->labelentity)->find($this->id);
        if (!$this->entity) throw $this->createNotFoundException('Unable to find entity.');
        $this->page = $this->entity->getPage();
        
        // Permissions
        if($this->access=="config") {
            $this->canupdate = true;
        }
        else {
            // On s'assure que l'utilisateur à la permission de voir
            $this->em->getRepository("CadolesPortalBundle:Page")->getPermission($this->user,$this->page,$this->cansee,$this->canupdate,$this->canadd);
            if(!$this->cansee) throw $this->createNotFoundException('Permission denied');
        }

        // Affichage miniature ?
        $this->mini = ($this->look=="list"&&$this->entity->getId()!=$this->selwidget);

        // Préference utilisateur
        if(!$this->mini && $this->page->getFgpreference()) $this->getPreference($this->entity);        
    }

    protected function getPreference(&$entity) {
        $user=$this->getUser();
        if($user) {
            $preference=$user->getPreference();
            $id=$entity->getId();

            // Preference widgetshowhide
            if($this->look=="list") {
                $entity->setOpened(true);
                $entity->setBorder(false);
            }
            else {
                if(is_array($preference)) {
                    if(array_key_exists("widgetshowhide",$preference)) {
                        if(array_key_exists($id,$preference["widgetshowhide"]))
                            $entity->setOpened(($preference["widgetshowhide"][$id]=="true"));
                    }
                }
            }
        }
    }

    protected function getKeyPreference(&$entity,$key,$value) {
        $user=$this->getUser();
        if(!$user) 
            return $value;
        
        $preference=$user->getPreference();
        $id=$entity->getId();

        if(!is_array($preference)) 
            return $value;

        if(!array_key_exists($key,$preference))
            return $value;
        
        if(!array_key_exists($id,$preference[$key]))
            return $value;
        
        return $preference[$key][$id];
    }    

    protected function getRender($view,$params) {
        // Paramétres toujours présent dans un rendu de widget
        $allways = [
            'entity'        => $this->entity,
            'canupdate'     => $this->canupdate,
            'access'        => $this->access,
            'look'          => $this->look,
            'mini'          => $this->mini,            
        ];

        // Parametres spéficiques
        $params=array_merge($allways,$params);

        // Rendu
        return $this->render($this->labelentity.':'.$view, $params);
    }

    public function viewurlAction(Request $request,$id,$access="config") {
        // Récupération de la requete
        $this->setRequest($request,$id,$access);

        // Valeur par défaut
        $url="";
        $imagemedia=false;

        // Datas associées au widget
        if(!$this->mini) {
            // Récupération des paramétres du widget
            foreach($this->entity->getParameter()["fields"] as $parameter) {
                if($parameter["id"]=="url")
                    $url=$parameter["value"];
            }

            // Gestion des url youtuve
            $url=str_replace("http://www.youtube.com","https://www.youtube.com",$url);
            $url=str_replace("https://www.youtube.com/watch?v=","https://www.youtube.com/embed/",$url);

            // Detecter le type de lien
            $pathinfo = pathinfo($url);

            // Type image
            if(array_key_exists("extension",$pathinfo)) { 
                if($pathinfo['extension']=="jpg"||$pathinfo['extension']=="gif"||$pathinfo['extension']=="png") {
                    $imagemedia=true;
                }
            }
            // Si url classique on igonore l'usage de la sonde dnma
            else {
                if(stripos($url,"?")===false)
                    $url.="?notsondednma=true";
                else
                    $url.="&notsondednma=true";
            }

            // Spécifique Deviant Art
            if(strpos($url, "images-wixmp") !== false) $imagemedia=true;
        }            
        
        return $this->getRender('viewurl.html.twig', [
            'url'           => $url,
            'imagemedia'    => $imagemedia,
        ]);
    }

    public function viewurlfixeAction(Request $request,$id,$access="config") {
        // Récupération de la requete
        $this->setRequest($request,$id,$access);

        // Valeur par défaut
        $url="";
        $imagemedia=false;

        // Datas associées au widget
        if(!$this->mini) {
            // Récupération des paramétres du widget
            $widgettype= $this->entity->getWidget();
            $jsons=$widgettype->getParameter();
            $param=array();
            $param["fields"]=array();
            foreach($jsons->fields as $field) {
                if($field->id=="url")
                    $url=$field->value;
            }

            // Gestion des url youtuve
            $url=str_replace("http://www.youtube.com","https://www.youtube.com",$url);
            $url=str_replace("https://www.youtube.com/watch?v=","https://www.youtube.com/embed/",$url);

            // Detecter le type de lien
            $pathinfo = pathinfo($url);

            // Type image
            if(array_key_exists("extension",$pathinfo)) { 
                if($pathinfo['extension']=="jpg"||$pathinfo['extension']=="gif"||$pathinfo['extension']=="png") {
                    $imagemedia=true;
                }
            }

            // Spécifique Deviant Art
            if(strpos($url, "images-wixmp") !== false) $imagemedia=true;            
        }

        return $this->getRender('viewurl.html.twig', [
            'url'           => $url,
            'imagemedia'    => $imagemedia,        
        ]);
    }

    public function viewitemAction(Request $request,$id,$access="config") {
        // Récupération de la requete
        $this->setRequest($request,$id,$access);

        // Valeur par défaut
        $modedesktop=0;
        $menu=false;
        $menuall=true;
        $search=false;
        $withbookmark=true;
        $bookmarks=null;
        $itemsordered=null;
        $itemcategorys=null;

        // Datas associées au widget
        if(!$this->mini) {      
           // Récupération des paramétres du widget
            $iditemcategory=null;
            foreach($this->entity->getParameter()["fields"] as $parameter) {
                switch($parameter["id"]) {
                    case "modedesktop":
                        $modedesktop=$parameter["value"];
                        break;

                    case "withbookmark":
                        $withbookmark=$parameter["value"];
                        break;

                    case "itemcategory":
                        $iditemcategory=$parameter["value"];
                        break;

                    case "search":
                        $search=($parameter["value"]==1);
                        break;

                    case "menu":
                        $menu=($parameter["value"]==1);
                        break;

                    case "menuall":
                        $menuall=($parameter["value"]==1);
                        break;

                }
            }
        
            // Préference utilisateur
            $modedesktop = $this->getKeyPreference($this->entity,"modedesktop",$modedesktop);
                        
            // Profilage
            $itemsordered = $this->em->getRepository("CadolesPortalBundle:Item")->getUserItems($this->user,$bookmarks,$items,$itemcategorys,$iditemcategory,$this->get('session')->get('ssoitems'),$withbookmark,false);
        }

        // Render
        return $this->getRender('viewitem.html.twig', [
            'canadd'        => ($this->user),
            'modedesktop'   => $modedesktop,
            'search'        => $search,
            'menu'          => $menu,
            'menuall'       => $menuall,
            'withbookmark'  => $withbookmark,
            'bookmarks'     => $bookmarks,
            'items'         => $itemsordered,
            'itemcategorys' => $itemcategorys,
        ]);
    }    

    public function viewitemessentialAction(Request $request,$id,$access="config") {
        // Récupération de la requete
        $this->setRequest($request,$id,$access);

        // Valeur par défaut
        $modedesktop=0;
        $itemsordered=null;
        $bookmarks=null;

        // Datas associées au widget
        if(!$this->mini) {  
            // Récupération des paramétres du widget
            foreach($this->entity->getParameter()["fields"] as $parameter) {
                switch($parameter["id"]) {
                    case "modedesktop":
                        $modedesktop=$parameter["value"];
                        break;
                }
            }
            
            // Préference utilisateur
            $modedesktop = $this->getKeyPreference($this->entity,"modedesktop",$modedesktop);

            // Profilage
            $itemsordered = $this->em->getRepository("CadolesPortalBundle:Item")->getUserItems($this->user,$bookmarks,$items,$itemcategorys,null,$this->get('session')->get('ssoitems'),0,true);
        }
       

        // Render
        return $this->getRender('viewitemessential.html.twig', [
            'canadd'        => ($this->user),
            'modedesktop'   => $modedesktop,
            'items'         => $itemsordered,
            'bookmarks'     => $bookmarks,        
        ]);
    }  

    public function viewalertAction(Request $request,$id,$access="config") {
        // Récupération de la requete
        $this->setRequest($request,$id,$access);

        // Valeur par défaut
        $alertsordered=null;

        // Datas associées au widget
        if(!$this->mini) {  
            // Récupération des paramétres du widget
            $idalertcategory=null;
            $alertcategoryfilter=null;
            foreach($this->entity->getParameter()["fields"] as $parameter) {
                switch($parameter["id"]) {
                    case "alertcategory":
                        $idalertcategory=$parameter["value"];
                        if($idalertcategory) $alertcategoryfilter=$this->em->getRepository("CadolesPortalBundle:Alertcategory")->find($idalertcategory);
                        break;
                }
            }
        
            // Profilage
            $alertsordered=$this->em->getRepository("CadolesPortalBundle:Alert")->getUserAlerts($this->user,$idalertcategory,$alertcategoryfilter,$this->get('session')->get('ssoitems'));
        }

        // Render
        return $this->getRender('viewalert.html.twig', [
            'alerts'        => $alertsordered,
        ]);
    }     

    public function viewfluxAction(Request $request,$id,$access="config") {
        // Récupération de la requete
        $this->setRequest($request,$id,$access);

        // Valeur par défaut
        $modelist=0;
        $fluxsordered=null;
        $feeds=null;

        // Datas associées au widget
        if(!$this->mini) {          
            // Récupération des paramétres du widget
            foreach($this->entity->getParameter()["fields"] as $parameter) {
                switch($parameter["id"]) {
                    case "modelist":
                        $modelist=$parameter["value"];
                        break;
                }
            }

            // Profilage
            $fluxs=$this->em->getRepository("CadolesPortalBundle:Flux")->getUserFluxs($this->user);
        
            $feeds=array();
            $filesystem = new Filesystem();

            // Généraltion du cache associés aux flux
            foreach($fluxs as $keyflux => $flux) {
                // On regarde si le flux a été lu il y a peu
                $toregen=true;
                $url=$flux->getUrl();

                // Feed lié à un user interne
                $filecache='uploads/flux/flux-'.$flux->getId().'.txt';
                if(stripos($url,"##userid##")!==false) {
                    if($user) {
                        $url=str_replace("##userid##",$user->getId(),$url);
                        $filecache=$filecache='uploads/flux/flux-'.$user->getId()."-".$flux->getId().'.txt';
                    }
                }

                // Si le fichie cache existe
                if($filesystem->exists($filecache)) {
                    // On récupère la date de modification du fichier
                    $timestampfile = filemtime($filecache);
                    $datetimeFormat = 'Y-m-d H:i:s';
                    $datefile = new \DateTime();
                    $datefile->setTimestamp($timestampfile);
        
                    // On ajoute 30mn
                    $datefile->add(new \DateInterval('PT30M'));
                    
                    // Si la date est inférieur à maintenant on regénère le flux
                    $now = new \DateTime();
                    if($datefile>=$now) {
                        $toregen=false;
                        $backup = unserialize(file_get_contents($filecache));
                        $feeds=array_merge($feeds,$backup);
                        if(empty($backup)) unset($fluxs[$keyflux]);                    
                    }
                }

                // Si le fichier est trop ancien on relit le flus
                if($toregen) {
                    $PROXYactivate = $this->em->getRepository("CadolesCoreBundle:Config")->find("PROXYactivate")->getValue();
                    $weburl=$this->getParameter('weburl');

                    if(stripos($url,"/")==0) {
                        $url="https://".$weburl.$url;
                        $PROXYactivate=false; 
                    }
                    if(stripos($url,"https://".$weburl)===0) $PROXYactivate=false; 
                    if(stripos($url,"http://".$weburl)===0) $PROXYactivate=false; 
                    
                    if($PROXYactivate) {
                        $PROXYserver    = $this->em->getRepository("CadolesCoreBundle:Config")->find("PROXYserver")->getValue();
                        $PROXYport      = $this->em->getRepository("CadolesCoreBundle:Config")->find("PROXYport")->getValue();
                        $clientguzzle = new \GuzzleHttp\Client(array('timeout' => 3,'verify'=>false,'proxy' => ['http'  => 'http://'.$PROXYserver.':'.$PROXYport,'https' => 'http://'.$PROXYserver.':'.$PROXYport]));
                    }
                    else
                        $clientguzzle = new \GuzzleHttp\Client(['timeout' => 3,'verify'=>false]);
        
                    try {
                        $clientguzzle->request('GET', $url);
                    } catch (RequestException $e) {
                        if ($e->hasResponse()) {
                            continue;
                        }
                    }
        
                    // On lit le flux rss
                    $client = new \FeedIo\Adapter\Guzzle\Client($clientguzzle);
                    $logger = new \Psr\Log\NullLogger();
                    $feedIo = new \FeedIo\FeedIo($client, $logger);

                    try {
                        $result     = $feedIo->read($url);
                    }
                    catch (\Exception $e) {
                        $result=null;
                    }
                    
                    if($result) {
                        $feedtitle  = $result->getFeed()->getTitle();
                        
                        
                        $backup=[];

                        // Pour chaque articles
                        $nbflux=0;
                        foreach ($result->getFeed() as $item) {
                            $title 			= $item->getTitle();
                            $link			= $item->getLink();
                            $description 	= substr(strip_tags($item->getDescription()),0,250);
                            $description    = str_replace("&para;","",$description);
                            $date 			= $item->getLastModified();
                            $dateformat		= ($date?$item->getLastModified()->format('d/m/Y H:i:s'):"");
                            $content 		= $item->getDescription();
                            $media          = $item->getMedias();
                            $mediaurl		= "";

                            foreach ($item->getMedias() as $itemMedia) {
                                if($itemMedia->getType()=="image/jpeg")
                                    $mediaurl=$itemMedia->getUrl();
                            }

                            foreach ($item->getAllElements() as $element) {

                                if($element->getName()=="content:encoded")
                                    $content = $element->getValue();
                            }

                            if($mediaurl!="") {
                                $imgurl=$mediaurl;
                            }
                            else {
                                // Récupérer la première image du contenu
                                $imgcontent="";
                                $imgurl="";
                                $imgstart = stripos($content,"<img");
                                if($imgstart!== false) {
                                    $imgend = stripos($content,">",$imgstart);
                                    $imgcontent=substr($content,$imgstart,$imgend-$imgstart+1);
                                
                                    $imgstart = stripos($imgcontent,"src=");
                                    $imgurl=substr($imgcontent,$imgstart+5);
                                    $imgend = stripos($imgurl,'"');

                                    if($imgend===false) $imgend = stripos($imgurl,"'");
                                    $imgurl=substr($imgurl,0,$imgend);
                                }
                            }

                            // Garder le flux
                            $tmp=array(
                                "feedtitle"		=> $feedtitle,
                                "title" 		=> $title,
                                "link"			=> $link,
                                "description"	=> $description,
                                "date"			=> $date,
                                "dateformat"	=> $dateformat,
                                "content"		=> $content,
                                "image"			=> $imgurl,
                                "color"         => $flux->getColor(),
                                "fluxid"        => $flux->getId(),
                                "fluxtitle"     => $flux->getTitle(),
                            );

                            array_push($feeds,$tmp);
                            array_push($backup,$tmp);

                            $nbflux++;
                            if($nbflux>=$flux->getMaxread()&&$flux->getMaxread()>0) break;
                        }


                        if($nbflux==0) unset($fluxs[$keyflux]);  
                        
                        // On sauvegarde le résultat en fichier on rechargera son contenu que s'il n'a pas été lu depuis 30mn
                        $filesystem->dumpFile($filecache, serialize($backup));
                    }
                }
            }

            // Trie des fluxs
            $fluxsordered = $fluxs->getIterator();
            $fluxsordered->uasort(function ($first, $second) {
                return (int) $first->getRowOrder() > (int) $second->getRowOrder() ? 1 : -1;
            });
                    
            // Trie des feeds
            $libelle=array();
            foreach ($feeds as $key => $valeur) {
                $libelle[$key] = $valeur["date"];
            }
            array_multisort($libelle, SORT_DESC, $feeds);
        }

        // Render
        return $this->getRender('viewflux.html.twig', [
            'modelist'      => $modelist,
            'fluxs'         => $fluxsordered,
            'feeds'         => $feeds,
        ]);
    }      

    public function viewrssAction(Request $request,$id,$access="config") {
        // Récupération de la requete
        $this->setRequest($request,$id,$access);  

        // Valeur par défaut
        $modelist=0;
        $fluxs=["id"=>0];
        $feeds=null;

        // Datas associées au widget
        if(!$this->mini) {          
            // Récupération des paramétres du widget
            $url="";
            $nbarticle="_blank";
            $modelist=0;
            foreach($this->entity->getParameter()["fields"] as $parameter) {
                switch($parameter["id"]) {
                    case "url":
                        $url=$parameter["value"];
                        break;
                    case "nbarticle":
                        $nbarticle=$parameter["value"];
                        break;           
                    case "modelist":
                        $modelist=$parameter["value"];
                        break;                             
                }
            }  

            // On regarde si le flux a été lu il y a peu
            $toregen=true;
            $filecache=$filecache='uploads/flux/widget-'.$id.'.txt';
            $user=$this->getUser();
            if(stripos($url,"##userid##")!==false) {
                if($user) {
                    $url=str_replace("##userid##",$user->getId(),$url);
                    $filecache=$filecache='uploads/flux/widget-'.$user->getId()."-".$id.'.txt';
                }
            }

            $filesystem = new Filesystem();
            if($filesystem->exists($filecache)) {
                // On récupère la date de modification du fichier
                $timestampfile = filemtime($filecache);
                $datetimeFormat = 'Y-m-d H:i:s';
                $datefile = new \DateTime();
                $datefile->setTimestamp($timestampfile);

                // On ajoute 30mn
                $datefile->add(new \DateInterval('PT30M'));
                
                // Si la date est inférieur à maintenant on regénère le flux
                $now = new \DateTime();
                if($datefile>=$now) {
                    $toregen=false;
                    $feeds = unserialize(file_get_contents($filecache));
                }
            }

            // Si le fichier est trop ancien on relit le flus
            if($toregen) {
                // Connexion au client
                $PROXYactivate = $this->em->getRepository("CadolesCoreBundle:Config")->find("PROXYactivate")->getValue();
                $weburl=$this->getParameter('weburl');
                if(stripos($url,"/")==0) {
                    $url="https://".$weburl.$url;
                    $PROXYactivate=false; 
                }
                if(stripos($url,"https://".$weburl)===0) $PROXYactivate=false; 
                if(stripos($url,"http://".$weburl)===0) $PROXYactivate=false;              

                if($PROXYactivate) {
                    $PROXYserver    = $this->em->getRepository("CadolesCoreBundle:Config")->find("PROXYserver")->getValue();
                    $PROXYport      = $this->em->getRepository("CadolesCoreBundle:Config")->find("PROXYport")->getValue();
                    $clientguzzle = new \GuzzleHttp\Client(array('timeout' => 3,'verify'=>false,'proxy' => ['http'  => 'http://'.$PROXYserver.':'.$PROXYport,'https' => 'http://'.$PROXYserver.':'.$PROXYport]));
                }
                else
                    $clientguzzle = new \GuzzleHttp\Client(array('timeout' => 3,'verify'=>false));

                try {
                    $clientguzzle->request('GET', $url);
                } catch (RequestException $e) {
                    if ($e->hasResponse()) {
                        // Render
                        $feeds=[];
                        return $this->getRender('viewflux.html.twig', [
                            'fluxs'         => $fluxs,
                            'feeds'         => $feeds,
                            'modelist'      => $modelist,
                        ]);
                    }
                }

                $client = new \FeedIo\Adapter\Guzzle\Client($clientguzzle);
                $logger = new \Psr\Log\NullLogger();
                $feedIo = new \FeedIo\FeedIo($client, $logger);

                $feeds=array();
                
                // On lit le flux rss
                try {
                    $result     = $feedIo->read($url);
                }
                catch (\Exception $e) {
                    $result=null;
                }

                if($result) {
                    $feedtitle  = $result->getFeed()->getTitle();
                    
                    
                    // Pour chaque articles
                    $nbflux=0;
                    foreach ($result->getFeed() as $item) {
                        $title 			= $item->getTitle();
                        $link			= $item->getLink();
                        $description 	= substr(strip_tags($item->getDescription()),0,250);
                        $description    = str_replace("&para;","",$description);
                        $date 			= $item->getLastModified();
                        $dateformat		= ($date?$item->getLastModified()->format('d/m/Y H:i:s'):"");
                        $content 		= $item->getDescription();
                        $media          = $item->getMedias();
                        $mediaurl		= "";

                        foreach ($item->getMedias() as $itemMedia) {
                            if($itemMedia->getType()=="image/jpeg")
                                $mediaurl=$itemMedia->getUrl();
                        }

                        foreach ($item->getAllElements() as $element) {
                            if($element->getName()=="content:encoded")
                                $content = $element->getValue();
                        }

                        if($mediaurl!="") {
                            $imgurl=$mediaurl;
                        }
                        else {
                            // Récupérer la première image du contenu
                            $imgcontent="";
                            $imgurl="";
                            $imgstart = stripos($content,"<img");
                            if($imgstart!== false) {
                                $imgend = stripos($content,">",$imgstart);
                                $imgcontent=substr($content,$imgstart,$imgend-$imgstart+1);
                                
                                $imgstart = stripos($imgcontent,"src=");
                                $imgurl=substr($imgcontent,$imgstart+5);
                                $imgend = stripos($imgurl,'"');

                                if($imgend===false) $imgend = stripos($imgurl,"'");
                                $imgurl=substr($imgurl,0,$imgend);
                            }
                        }
                        
                        // Garder le flux
                        array_push($feeds,array(
                            "feedtitle"		=> $feedtitle,
                            "title" 		=> $title,
                            "link"			=> $link,
                            "description"	=> $description,
                            "date"			=> $date,
                            "dateformat"	=> $dateformat,
                            "content"		=> $content,
                            "image"			=> $imgurl,
                            // "color"         => $flux->getColor(),
                            "fluxid"        => 0,
                            "fluxtitle"     => $this->entity->getName(),
                            ));

                        $nbflux++;
                        if($nbflux>=$nbarticle&&$nbarticle>0) break;
                    }


                    $libelle=array();
                    foreach ($feeds as $key => $valeur) {
                        $libelle[$key] = $valeur["date"];
                    }
                    array_multisort($libelle, SORT_DESC, $feeds);

                    // On sauvegarde le résultat en fichier on rechargera son contenu que s'il n'a pas été lu depuis 30mn
                    $filesystem->dumpFile($filecache, serialize($feeds));
                }
            }
        }

        // Render
        return $this->getRender('viewflux.html.twig', [
            'fluxs'         => $fluxs,
            'feeds'         => $feeds,
            'modelist'      => $modelist,
        ]);
    }  

    public function viewbookmarkAction(Request $request,$id,$access="config") {
        // Récupération de la requete
        $this->setRequest($request,$id,$access);

        // Valeur par défaut 
        $modedesktop=0;
        $bookmarks=null;        

        // Datas associées au widget
        if(!$this->mini) {  
            // Récupération des paramétres du widget
            foreach($this->entity->getParameter()["fields"] as $parameter) {
                switch($parameter["id"]) {
                    case "modedesktop":
                        $modedesktop=$parameter["value"];
                        break;
                }
            }
            
            // Bookmark du widget
            $bookmarks=$this->em->getRepository("CadolesPortalBundle:Bookmark")->findBy(["pagewidget"=>$this->entity]);
        }

        // Render
        return $this->getRender('viewbookmark.html.twig', [
            'canadd'        => $this->canadd,
            'modedesktop'   => $modedesktop,
            'bookmarks'     => $bookmarks,
        ]);
    }   

    public function viewlinkAction(Request $request,$id,$access="config") {
        // Récupération de la requete
        $this->setRequest($request,$id,$access);

        // Récupération des paramétres du widget
        $url="";
        $target="_blank";
        foreach($this->entity->getParameter()["fields"] as $parameter) {
            switch($parameter["id"]) {
                case "url":
                    $url=$parameter["value"];
                    break;
                case "target":
                    $target=$parameter["value"];
                    break;                    
            }
        }

        // Render
        return $this->getRender('viewlink.html.twig', [
            'canadd'        => false,
            'url'           => $url,
            'target'        => $target,
        ]);
    }       

    public function vieweditorAction(Request $request,$id,$access="config") {
        // Récupération de la requete
        $this->setRequest($request,$id,$access);

        // Récupération des paramétres du widget
        $html="";
        foreach($this->entity->getParameter()["fields"] as $parameter) {
            switch($parameter["id"]) {
                case "html":
                    $html=$parameter["value"];
                    break;
                 
            }
        }

        // Render
        return $this->getRender('vieweditor.html.twig', [
            'canadd'        => false,
            'html'          => $html,
        ]);
    }   

    public function viewslideAction(Request $request,$id,$access="config") {
        // Récupération de la requete
        $this->setRequest($request,$id,$access);
        
        // Récupération des paramétres du widget
        $interval="2";
        foreach($this->entity->getParameter()["fields"] as $parameter) {
            switch($parameter["id"]) {
                case "interval":
                    $interval=$parameter["value"];
                    break;                
            }
        }
        
        // Récupération des slides
        $slides=$this->em->getRepository("CadolesPortalBundle:Slide")->findBy(["pagewidget"=>$this->entity],['roworder'=>'ASC','title'=>'ASC']);

        // Render
        return $this->getRender('viewslide.html.twig', [
            'canadd'        => $this->canadd,
            'slides'        => $slides,
            'interval'      => $interval,
        ]);
    }    

    public function viewfileAction(Request $request,$id,$access="config") {
        // Récupération de la requete
        $this->setRequest($request,$id,$access);
        
        // Récupération des paramétres du widget
        $view="small";
        foreach($this->entity->getParameter()["fields"] as $parameter) {
            switch($parameter["id"]) {
                case "modelist":
                    $view=($parameter["value"]==0?"small":"list");
                    break;                
            }
        }

        // Render
        return $this->getRender('viewfile.html.twig', [
            'canadd'        => $this->canadd,
            'directory'     => "widget-".$id,
            'view'          => $view,
        ]);       
    }
    
    public function viewgaleryAction(Request $request,$id,$access="config") {
        // Récupération de la requete
        $this->setRequest($request,$id,$access);

        $directory=$this->get('kernel')->getRootDir()."/../uploads/file/widget-".$id;
        $files=[];
        $fs = new Filesystem();

        if($fs->exists($directory)) {
            $finder = new Finder();
            $finder->sortByName()->in($directory)->exclude('thumb')->exclude('thumbmini');
            
            foreach ($finder as $file) {
                $tmp=[];
                $tmp["name"]=$file->getRelativePathname();
                $tmp["extension"]=$file->getExtension();
                $fileinfo = new file($file->getPathname());
                $tmp["minetype"]=$fileinfo->getMimeType();
                $tmp["minefamily"]=explode("/",$tmp["minetype"])[0];

                $tmp["thumb"]="";
                if($fs->exists($directory."/thumb/".$tmp["name"])) {
                    $data = file_get_contents($directory."/thumb/".$tmp["name"]);
                    $tmp["thumb"]="data:image/" . $tmp["extension"] . ";base64," . base64_encode($data);
                }

                array_push($files,$tmp);
            }
        }

        
        // Render
        return $this->getRender('viewgalery.html.twig', [
            'canadd'        => $this->canadd,
            'files'         => $files,
        ]);
    }    

    public function viewcalendarAction(Request $request,$id,$access="config") {
        // Récupération de la requete
        $this->setRequest($request,$id,$access);

        // Récupération des paramétres du widget
        $nbday="0";
        foreach($this->entity->getParameter()["fields"] as $parameter) {
            switch($parameter["id"]) {
                case "nbday":
                    $nbday=$parameter["value"];
                    break;                
            }
        }
        
        // Récupérer les events de l'utilisateur
        $user=$this->getUser();
        $events=$this->em->getRepository("CadolesPortalBundle:Calendarevent")->getUserCalendarevents($user,$this->get('session')->get('color')["main"],$this->usage,$this->group,$firstcalendar);

        // Render
        return $this->getRender('viewcalendar.html.twig', [
            'canadd'        => $this->canadd,
            'events'        => $events,
            'nbday'         => $nbday,
            'firstcalendar' => $firstcalendar,
            'usage'         => $this->usage,
        ]);
    }  

    public function viewblogAction(Request $request,$id,$access="config") {
        // Récupération de la requete
        $this->setRequest($request,$id,$access);

        // Récupération des paramétres du widget
        $nbarticle=10;
        foreach($this->entity->getParameter()["fields"] as $parameter) {
            switch($parameter["id"]) {
                case "nbarticle":
                    $nbarticle=$parameter["value"];
                    break;                
            }
        }

        // On récupère soit les blogs du group en cours soit l'ensemble des blogs de l'utilisateur
        if($this->usage=="group") {
            $blogs=$this->em->getRepository("CadolesPortalBundle:Blog")->getBlogsGroup($this->getUser(),$this->group);
            if($blogs) $firstblog=$blogs[0]->getId();
        }
        else {
            $this->em->getRepository("CadolesPortalBundle:Blog")->getBlogsUser($this->getUser(),$blogsuser,$blogsadmin,$blogsshared);
            $blogs=array_merge($blogsuser,$blogsadmin->toArray(),$blogsshared);
            $firstblog="all";
        }

        // On récupère les nbarticle de ses blogs
        $this->em->getRepository("CadolesPortalBundle:Blogarticle")->getBlogsArticles($blogs,0,$nbarticle,$count,$blogarticles);


        // Render
        return $this->getRender('viewblog.html.twig', [
            'canadd'        => $this->canadd,
            'blogarticles'  => $blogarticles,
            'nbarticle'     => $nbarticle,
            'firstblog'     => $firstblog,
            'usage'         => $this->usage,
        ]);
    }  

    public function viewprojectAction(Request $request,$id,$access="config") {
        // Récupération de la requete
        $this->setRequest($request,$id,$access);

        // Parametres
        $nbarticle=10;
        foreach($this->entity->getParameter()["fields"] as $parameter) {
            switch($parameter["id"]) {
                case "nbarticle":
                    $nbarticle=$parameter["value"];
                    break;                
            }
        }

        // On récupère soit les projects du group en cours soit l'ensemble des projects de l'utilisateur
        $user=$this->getUser();
        if($this->usage=="group") {
            $projects=$this->em->getRepository("CadolesPortalBundle:Project")->getProjectsGroup($this->getUser(),$this->group);
            if($projects) $firstproject=$projects[0]->getId();
        }
        else {
            $this->em->getRepository("CadolesPortalBundle:Project")->getProjectsUser($user,$projectsuser,$projectsadmin,$projectsshared);
            $projects=array_merge($projectsuser,$projectsadmin->toArray(),$projectsshared);
            $firstproject="all";
        }
       
        // On récupère les nbarticle de ses projects
        $this->em->getRepository("CadolesPortalBundle:Projecttask")->getProjectsTasks($projects,0,$nbarticle,$count,$projecttasks);

        foreach($projecttasks as $key => $projecttask) {
            if($projecttask->getPercentage()==100) unset($projecttasks[$key]);
        }

        if($this->usage!="group") {
            foreach($projecttasks as $key => $projecttask) {
                if(!$user) unset($projecttasks[$key]);
                else {
                    if($projecttask->getUser() && $projecttask->getUser()!=$user)
                        unset($projecttasks[$key]);
                    elseif(!$projecttask->getUser() && $projecttask->getOwner() && $projecttask->getOwner()!=$user) 
                        unset($projecttasks[$key]);

                }
            }
        }

        // Render
        return $this->getRender('viewproject.html.twig', [
            'canadd'        => $this->canupdate,
            'projecttasks'  => $projecttasks,
            'nbarticle'     => $nbarticle,
            'firstproject'  => $firstproject,
            'usage'         => $this->usage,
        ]);
    }  

    public function viewseparatorAction(Request $request,$id,$access="config") {
        // Récupération de la requete
        $this->setRequest($request,$id,$access);
        
        // Parametres
        $seetitle=false;
        $seeicon=false;
        foreach($this->entity->getParameter()["fields"] as $parameter) {
            switch($parameter["id"]) {
                case "seetitle":
                    $seetitle=boolval($parameter["value"]);
                    break;     
                case "seeicon":
                    $seeicon=boolval($parameter["value"]);
                    break;                                    
            }
        }

        // Render
        return $this->getRender('viewseparator.html.twig', [
            'canadd'        => $this->canupdate,
            'seetitle'      => $seetitle,
            'seeicon'       => $seeicon,
        ]);
    } 

    public function viewclockAction(Request $request,$id,$access="config") {
        // Récupération de la requete
        $this->setRequest($request,$id,$access);
        
        // Parametres
        $clock="0";
        foreach($this->entity->getParameter()["fields"] as $parameter) {
            switch($parameter["id"]) {
                case "clock":
                    $clock=$parameter["value"];
                    break;                
            }
        }

        // Render
        return $this->getRender('viewframe.html.twig', [
            'canadd'        => $this->canupdate,
            'onheader'      => true,
            'tool'          => ($clock==0?"cadoles_portal_user_tool_clockanalogique":"cadoles_portal_user_tool_clocknumerique"),
        ]);
    }  

    public function viewcalculatorAction(Request $request,$id,$access="config") {
        // Récupération de la requete
        $this->setRequest($request,$id,$access);

        // Render
        return $this->getRender('viewframe.html.twig', [
            'canadd'        => $this->canupdate,
            'onheader'      => true,
            'tool'          => "cadoles_portal_user_tool_calculator",          
        ]);
    }            

    public function viewappexternalAction(Request $request,$id,$access="config") {
        // Récupération de la requete
        $this->setRequest($request,$id,$access);

        // Récupération des paramétres du widget
        $idappexternal=null;
        foreach($this->entity->getParameter()["fields"] as $parameter) {
            switch($parameter["id"]) {
                case "appexternal":
                    $idappexternal=$parameter["value"];
                    break;
                case "modedesktop":
                    $modedesktop=$parameter["value"];
                    break;                
            }
        }
        
        $user=$this->getUser();
        $items=[];
        $itemcategorys=[];
        if($user) {
            if($idappexternal) $appextenals=$this->em->getRepository("CadolesPortalBundle:Appexternal")->findBy(["id"=>$idappexternal]);
            else  $appextenals=$this->em->getRepository("CadolesPortalBundle:Appexternal")->findAll();
            foreach($appextenals as $appexternal) {
                switch($appexternal->getName()) {
                    case "Limesurvey":
                        $category=["id"=>0,"label"=>"Limesurvey"];
                        array_push($itemcategorys,$category);

                        $directory=$this->get('kernel')->getRootDir()."/../uploads/limesurvey/".$user->getId();
                        $files=[];
                        $fs = new Filesystem();

                        if($fs->exists($directory."/invitation.json")) {
                            $file=file_get_contents($directory."/invitation.json");
                            $json = substr($file, 0, -2);  // sup dernier ,
                            $surveys = json_decode("{".$json."}", true);
                            if(is_array($surveys)) {
                                foreach($surveys as $id => $survey) {
                                    array_push($items,["id"=>$id,"title"=>$survey["title"],"subtitle"=>"Sondage","url"=>$survey["url"],"itemcategory"=>$category,"color"=>"328637","icon"=>"icon_limesurvey.png"]);
                                }
                            }
                        }

                        break;

                    case "Moodle":
                        $category=["id"=>1,"label"=>"Moodle"];
                        array_push($itemcategorys,$category);

                        $directory=$this->get('kernel')->getRootDir()."/../uploads/moodle/".$user->getId();
                        $files=[];
                        $fs = new Filesystem();

                        if($fs->exists($directory."/invitation.json")) {
                            $file=file_get_contents($directory."/invitation.json");
                            $json = substr($file, 0, -2);  // sup dernier ,
                            $courses = json_decode("{".$json."}", true);
                            if(is_array($courses)) {
                                foreach($courses as $id => $course) {
                                    array_push($items,["id"=>$id,"title"=>$course["title"],"subtitle"=>"Cours","url"=>$course["url"],"itemcategory"=>$category,"color"=>"f77f11","icon"=>"icon_moodle.png"]);
                                }
                            }
                        }

                        break;                        
                }
            }
        }

        // Trier les item par title
        $title  = array_column($items, 'title');
        array_multisort($title, SORT_ASC, $items);

        // Render
        return $this->getRender('viewappexternal.html.twig', [
            'canadd'        => ($user),
            'modedesktop'   => $modedesktop,
            'items'         => $items,
            'itemcategorys' => $itemcategorys,         
        ]);
    }     

    public function viewinfoAction(Request $request,$id,$access="config") {
        // Récupération de la requete
        $this->setRequest($request,$id,$access);

        $icon=null;
        $title=null;
        $description=null;
        $members=[];
        if($this->usage=="group") {
            $groupentity=$this->em->getRepository("CadolesCoreBundle:Group")->find($this->group);
            if($groupentity) {
                $title=$this->entity->getPage()->getName();
                $id=$groupentity->getId();
                if($groupentity->getDescription())
                    $description="<strong>Description</strong><br>".$groupentity->getDescription();
                if($groupentity->getIcon())
                    $icon="/".$groupentity->getIcon()->getLabel();
                
                    
                foreach($groupentity->getUsers() as $usergroup) {
                    array_push($members,$usergroup);
                }
            }
        }
        else {
            $title=$this->entity->getPage()->getName();
            $proprio=$this->entity->getPage()->getUser();
            $id=0;
            if($proprio) {
                $description="Propriétaire de la page<br>".$proprio->getLastname()." ".$proprio->getLastname();
                $icon="/uploads/avatar/".$proprio->getAvatar();
            }
        }

        // Render
        return $this->getRender('viewinfo.html.twig', [
            'canadd'        => $this->canupdate,
            'usage'         => $this->usage,
            'icon'          => $icon,
            'title'         => $title,
            'description'   => $description,
            'members'       => $members,
            'id'            => $id,
            'idpage'        => $this->entity->getPage()->getId(),   
        ]);
    }     

    public function viewchatAction(Request $request,$id,$access="config") {
        // Récupération de la requete
        $this->setRequest($request,$id,$access);

        $group=$this->group;
        if($this->usage!="group"||!$group) {
            $group=$this->em->getRepository("CadolesCoreBundle:Group")->findOneBy(["fgall"=>true])->getId();
        }

        // Render
        return $this->getRender('viewchat.html.twig', [
            'canadd'        => $this->canupdate,
            'onheader'      => false,
            'tool'          => "cadoles_websocket_chat",
            'usage'         => $this->usage,
            'group'         => $group,
        ]);
    } 


    public function viewgroupAction(Request $request,$id,$access="config") {
        // Récupération de la requete
        $this->setRequest($request,$id,$access);

        $user=$this->getUser();
        $mygroups=[];
        $this->getDoctrine()->getRepository("CadolesPortalBundle:Page")->getPagesUser($user,null,$default,$pagesuser,$pagesadmin,$groupsshared);
        if(is_array($groupsshared)) {
            foreach($groupsshared as $groupshared) {

                $title=$groupshared->getLabel();
                $idpage=$groupshared->pagesshared[0]->getId();
                $color=$groupshared->getColor();
                $icon=null;
                if($groupshared->getIcon())
                    $icon="/".$groupshared->getIcon()->getLabel();  

                array_push($mygroups,["title"=>$title,"icon"=>$icon,"id"=>$idpage,"color"=>$color]);
            }
        }
        
        // Render
        return $this->getRender('viewgroup.html.twig', [
            'canadd'        => ($user),
            'usage'         => $this->usage,
            'groups'        => $mygroups,
        ]);
    }  
    
    public function viewgroupmessageAction(Request $request,$id,$access="config") {
        // Récupération de la requete
        $this->setRequest($request,$id,$access);  
        
        // Récupération des paramétres du widget
        $modelist=1;
        $nbarticle=5;
        foreach($this->entity->getParameter()["fields"] as $parameter) {
            switch($parameter["id"]) {     
                case "modelist":
                    $modelist=$parameter["value"];
                    break;                             
                case "nbarticle":
                    $nbarticle=$parameter["value"];
                    break;                             
            }
        }  

        $mymsg= [];
        $user=$this->getUser();
        $this->getDoctrine()->getRepository("CadolesPortalBundle:Page")->getPagesUser($user,null,$default,$pagesuser,$pagesadmin,$groupsshared);
        if(is_array($groupsshared)) {
            foreach($groupsshared as $groupshared) {
                // On récupère les info du groupe
                $title=$groupshared->getLabel();
                $idpage=$groupshared->pagesshared[0]->getId();
                $color=$groupshared->getColor();

                // On récupère l'ensemble des messages du groupes
                $messages=$this->getDoctrine()->getRepository("CadolesWebsocketBundle:Message")->findBy(["group"=>$groupshared]);
                foreach($messages as $key => $message) {
                    // persistante collection à revoir
                    if($message->getSees()->count()>0) {
                        if($message->getSees()->contains($user) ) {

                            unset($messages[$key]);
                        }
                    }
                }

                foreach($messages as $key => $message) {
                    $tmp=["id" => $message->getId(), "user" => $message->getUser(), "date"=>$message->getSubmitdate(), "topic"=>$message->getTopic(), "pageid" => $idpage, "pagetitle" => $title, "color" => $color];
                    array_push($mymsg,$tmp);   
                }
            }
            
            $ord = array();
            foreach ($mymsg as $key => $value){
                $ord[] = $value['date'];
            }
            array_multisort($ord, SORT_DESC, $mymsg);
        }

        
        // Render
        return $this->getRender('viewgroupmessage.html.twig', [
            'canadd'        => ($user),
            'usage'         => $this->usage,
            'modelist'      => $modelist,
            'messages'      => $mymsg, 
            'nbarticle'     => $nbarticle,
        ]);
    } 
    
    public function viewOnlydocAction(Request $request,$id,$access="config") {
        // Récupération de la requete
        $this->setRequest($request,$id,$access);       
       
        // Récupération des paramétres du widget
        $apponly=0;
        $view="small";
        foreach($this->entity->getParameter()["fields"] as $parameter) {
            switch($parameter["id"]) {     
                case "apponly":
                    $apponly=$parameter["value"];
                    break;         
                case "modelist":
                    $view=($parameter["value"]==0?"small":"list");
                    break;                                           
            }
        } 
               
        return $this->getRender('viewonlydoc.html.twig', [
            'canadd'        => $this->canupdate,
            'directory'     => $id,
            'view'          => $view,
        ]);          
    }    
}



