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

651 lines
34 KiB
PHP

<?php
namespace Cadoles\CoreBundle\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\HttpFoundation\Response;
use Doctrine\DBAL\Connection as DBALConnection;
use Doctrine\ORM\EntityManager;
use Ramsey\Uuid\Uuid;
use Ramsey\Uuid\Exception\UnsatisfiedDependencyException;
use Cadoles\CoreBundle\Entity\Niveau01;
use Cadoles\CoreBundle\Entity\Niveau02;
use Cadoles\CoreBundle\Entity\User;
use Cadoles\CoreBundle\Entity\Group;
use Cadoles\CoreBundle\Entity\UserGroup;
use Cadoles\PortalBundle\Entity\Calendar;
use Cadoles\PortalBundle\Entity\Blog;
use Cadoles\PortalBundle\Entity\Project;
use Unirest\Request;
global $bdd01;
global $config;
class OnlyCommand extends Command
{
private $container;
private $em;
private $output;
private $filesystem;
private $rootlog;
private $only_activate;
private $only_sync;
private $only_url;
private $only_host;
private $only_user;
private $only_password;
protected function configure()
{
$this
->setName('Core:Only')
->setDescription('Synchronisation Only Office')
->setHelp('This command Synchro Only Office for Core')
->addArgument('simulate', InputArgument::OPTIONAL, 'true to simulate / false to run')
->addArgument('cronid', InputArgument::OPTIONAL, 'ID Cron Job')
->addArgument('lastchance', InputArgument::OPTIONAL, 'Lastchance to run the cron')
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->container = $this->getApplication()->getKernel()->getContainer();
$this->em = $this->container->get('doctrine')->getEntityManager();
$this->output = $output;
$this->filesystem = new Filesystem();
$this->rootlog = $this->container->get('kernel')->getRootDir()."/../var/logs/";
$this->writelnred('');
$this->writelnred('== Core:Only');
$this->writelnred('==========================================================================================================');
setlocale( LC_CTYPE, 'fr_FR' );
$simulate = $input->getArgument('simulate');
if($simulate=="") $simulate="true";
if($simulate!="true"&&$simulate!="false") {
$this->writeln('Paramétre incorrect');
return;
}
$simulate=($simulate=="true");
$this->writeln('');
if($simulate) $this->writeln('** SIMULATION');
else $this->writeln('** REEL');
$this->writeln('');
$this->writeln('=====================================================');
$this->writeln('== SYNCHONISATION ONLY OFFICE =======================');
$this->writeln('=====================================================');
$this->only_activate = $this->container->getParameter("activate_widonlyoffice");
if(!$this->only_activate) {
$this->writeln('Synchronisation Only désactivé');
return 1;
}
$this->only_sync = $this->container->getParameter("widonlyoffice_sync");
if(!$this->only_sync) {
$this->writeln('Synchronisation Only désactivé');
return 1;
}
$this->only_sync = true;
$this->only_url = $this->container->getParameter("widonlyoffice_url")."/api/2.0/";
$this->only_host = str_replace("https://","",str_replace("http://","",$this->container->getParameter("widonlyoffice_url")));
$this->only_user = $this->container->getParameter("widonlyoffice_user");
$this->only_password = $this->container->getParameter("widonlyoffice_password");
$this->writeln($this->only_url);
$this->writeln($this->only_host);
$this->writeln($this->only_user);
if($this->only_sync) {
// Only Office est-il dans le domaine
if(stripos($this->only_url,"/")===0)
$this->only_url="https://".$this->container->getParameter("weburl").$this->only_url;
$indomaine = (stripos($this->only_url,$this->container->getParameter("weburl"))!==false);
// Si hors domaine on utilise le proxy si proxy il y a
if(!$indomaine) {
$PROXYactivate = $this->em->getRepository("CadolesCoreBundle:Config")->find("PROXYactivate")->getValue();
if($PROXYactivate) {
$PROXYserver = $this->em->getRepository("CadolesCoreBundle:Config")->find("PROXYserver")->getValue();
$PROXYport = $this->em->getRepository("CadolesCoreBundle:Config")->find("PROXYport")->getValue();
\Unirest\Request::proxy($PROXYserver, $PROXYport, CURLPROXY_HTTP, true);
}
}
// Authentification à onlyoffice
$this->writeln('');
$this->writeln('== AUTHENTIFICATION =================================');
\Unirest\Request::verifyPeer(false);
\Unirest\Request::verifyHost(false);
\Unirest\Request::timeout(20);
$headers = ['Host' => $this->only_host, 'Accept' => 'application/json','Content-Type'=>'application/json','Retry-After'=>'5'];
$query = array('userName' => $this->only_user, 'password' => $this->only_password);
$body = \Unirest\Request\Body::json($query);
$response = \Unirest\Request::post($this->only_url.'/authentication',$headers,$body);
if($this->koresponse($response)) return 0;
$token=$response->body->response->token;
$headers["Authorization"]=$token;
// Synchronisation des utilisateur Only sur l'annuaire
$this->writeln('');
$this->writeln('== SYNCHRONISATION ONLY==============================');
$response = \Unirest\Request::get($this->only_url.'/settings/ldap/sync',$headers);
if($this->koresponse($response)) return 0;
// Fichier d'import des utilisateurs only inexistant dans ninegate
$this->filesystem->remove($this->rootlog.'toimportfromonly.csv');
$string="login;prenom;nom;email;niveau01;role";
$this->filesystem->appendToFile($this->rootlog.'toimportfromonly.csv', $string."\n");
// Controler les utilisateur only
$this->writeln('');
$this->writeln('== CONTROLE USER ONLY================================');
$kousers=[];
$onlyusers=[];
$start=0;
$response = \Unirest\Request::get($this->only_url.'/people',$headers);
if($this->koresponse($response)) return 0;
$peoples=$response->body->response;
while(isset($response->body->nextIndex)) {
$response = \Unirest\Request::get($this->only_url.'/people?startIndex='.$response->body->nextIndex,$headers);
if($this->koresponse($response)) return 0;
$peoples=array_merge($peoples,$response->body->response);
}
foreach($peoples as $onlyuser) {
$user=$this->em->getRepository("CadolesCoreBundle:User")->findBy(["username"=>$onlyuser->userName]);
if(!$user) {
$this->writelnred("ERREUR ".$onlyuser->userName." existe dans OnlyOffice mais pas dans Ninegate");
$string=$onlyuser->userName.";".$onlyuser->firstName.";".$onlyuser->lastName.";".$onlyuser->email.";Autres;ROLE_USER";
$this->filesystem->appendToFile($this->rootlog.'toimportfromonly.csv', $string."\n");
}
else {
// Sauvegarde l'id du useronlyoffice
$onlyusers[$onlyuser->id]=$onlyuser->userName;
}
}
// Controler les utilisateurs ninegate
$this->writeln('');
$this->writeln('== CONTROLE USER NINEGATE============================');
/*
$users=$this->em->getRepository("CadolesCoreBundle:User")->findAll();
foreach($users as $user) {
$response = \Unirest\Request::get($this->only_url.'/people/'.$user->getUsername(),$headers);
if($this->koresponse($response)) {
$this->writelnred("ERREUR ".$user->getUsername()." existe dans Ninegate mais pas dans OnlyOffice");
}
}
*/
// On recherche la page template de group
$pagetemplate=$this->em->getRepository("CadolesPortalBundle:Page")->findOneBy(["parentfor"=>"group"]);
if(!$pagetemplate) {
$this->writelnred("ERREUR Pas de page modèle de type groupe");
return 1;
}
// Injection des groupes only non existant dans ninegate
$this->writeln('');
$this->writeln('== INJECTION DES GROUPES ONLY========================');
$response = \Unirest\Request::get($this->only_url.'/project?status=0,',$headers);
if($this->koresponse($response)) return 0;
$projects=$response->body->response;
while(isset($response->body->nextIndex)) {
$response = \Unirest\Request::get($this->only_url.'/project?status=0&startIndex='.$response->body->nextIndex,$headers);
if($this->koresponse($response)) return 0;
$projects=array_merge($projects,$response->body->response);
}
foreach($projects as $onlygroup) {
// On ne scanne que les groupe ouvert
if($onlygroup->status!=0)
continue;
// Le groupe existe-t-il dans ninegate
$group=$this->em->getRepository("CadolesCoreBundle:Group")->findBy(["idonlyoffice"=>$onlygroup->id]);
if(!$group) {
$namegroup=$onlygroup->id." - ".$onlygroup->title;
// On enlève les caractères interdis
$namegroup=preg_replace('~[^ éèêôöàïî\'@a-zA-Z0-9._-]~', '', $namegroup);
// Ce nom de groupe existe-t-il déjà si oui erreur
$group=$this->em->getRepository("CadolesCoreBundle:Group")->findBy(["label"=>$namegroup]);
if($group)
$this->writelnred("ERREUR Groupe déjà existant = ".$namegroup);
else{
// Le propriétaire du groupe only existe-t-il dans ninegate
if(!array_key_exists($onlygroup->responsible->id,$onlyusers)) {
if(!array_key_exists($onlygroup->responsible->id,$kousers)) {
// Comme on n'a que les 1000 permiers lors du parcours des users only peut etre que lui fait partie de ceux que l'on n'a pas scanné
$respuser = \Unirest\Request::get($this->only_url.'/people/'.$onlygroup->responsible->id,$headers);
// Là normalement on a forcement une réponse positive
if(!$this->koresponse($respuser)) {
$onlyuser=$respuser->body->response;
$user=$this->em->getRepository("CadolesCoreBundle:User")->findBy(["username"=>$onlyuser->userName]);
if(!$user) {
$kousers[$onlygroup->responsible->id]=$onlygroup->responsible->displayName;
$string=$onlyuser->userName.";".$onlyuser->firstName.";".$onlyuser->lastName.";".$onlyuser->email.";Autres;ROLE_USER";
$this->filesystem->appendToFile($this->rootlog.'toimportfromonly.csv', $string."\n");
}
else {
// Sauvegarde l'id du useronlyoffice
$onlyusers[$onlyuser->id]=$onlyuser->userName;
}
}
}
}
// Le propriétaire du groupe only existe-t-il dans ninegate
if(!array_key_exists($onlygroup->responsible->id,$onlyusers)) {
$this->writelnred("ERREUR Propriétaire du Groupe n'existe pas. Group = ".$namegroup. " - User = ".$onlygroup->responsible->displayName);
}
else {
// Création du groupe
$user=$this->em->getRepository("CadolesCoreBundle:User")->findOneBy(["username"=>$onlyusers[$onlygroup->responsible->id]]);
$this->writeln("Création du groupe Ninegate = ".$namegroup);
if(!$simulate) {
$group=new Group();
$group->setLabel($namegroup);
$group->setDescription($onlygroup->description);
$group->setFgopen(false);
$group->setFgcanshare(true);
$group->setFgcancreatepage(false);
$group->setFgcancreatecalendar(false);
$group->setFgcancreateblog(false);
$group->setFgcancreateproject(false);
$group->setFgall(false);
$group->setFgtemplate(false);
$group->setOwner($user);
$group->setPagetemplate($pagetemplate);
$group->setIdonlyoffice($onlygroup->id);
$group->setNosynconly(true);
$this->em->persist($group);
$this->em->flush();
// On ajoute le propriétaire en tant que membre du groupe
$this->addMember($group,$user,100);
// On controle que le groupe a bien page / calendrier / blog / project
$this->ctrlFgcanshare($group,$user,$pagetemplate);
}
// Rattachement des membres au groupe
$group=$this->em->getRepository("CadolesCoreBundle:Group")->findOneBy(["idonlyoffice"=>$onlygroup->id]);
$members = \Unirest\Request::get($this->only_url.'/project/'.$onlygroup->id.'/team',$headers);
if($this->koresponse($members)) return 0;
foreach($members->body->response as $member) {
// Si non propriétaire du groupe
if($member->userName!=$onlyusers[$onlygroup->responsible->id]) {
$user=$this->em->getRepository("CadolesCoreBundle:User")->findOneBy(["username"=>$member->userName]);
if(!$user) {
$this->writelnred("ERREUR Membre du group inexistant. Group = ".$namegroup." - ".$member->userName);
if(!array_key_exists($member->id,$kousers)) {
$kousers[$member->id]=$member->displayName;
$string=$member->userName.";".$member->firstName.";".$member->lastName.";".$member->email.";Autres;ROLE_USER";
$this->filesystem->appendToFile($this->rootlog.'toimportfromonly.csv', $string."\n");
}
}
else {
$this->writeln("Rattachement utilisateur. Group = ".$namegroup." - User = ".$member->userName);
if(!$simulate&&$group) {
// On s'assure qu'il n'es pas déjà rattaché
$usergroup=$this->em->getRepository("CadolesCoreBundle:UserGroup")->findOneBy(["user"=>$user,"group"=>$group]);
if(!$usergroup) {
$this->addMember($group,$user,0);
}
}
}
}
}
if(!$simulate) {
$this->em->persist($group);
$this->em->flush();
}
}
}
}
}
// Injection des groupes ninegate non existant dans only
$this->writeln('');
$this->writeln('== INJECTION DES GROUPES NINEGATE====================');
$groups=$this->em->getRepository("CadolesCoreBundle:Group")->findBy(["fgcanshare"=>true]);
foreach($groups as $group) {
// Info du groupe
$grouptitle=$group->getLabel();
$groupdescription=$group->getDescription();
$groupowner=$group->getOwner();
$groupisprivate=true;
$tocreate=false;
// Si pas de propriétaire de projet on le rattache à admin
if(!$groupowner)
$groupowner=$this->em->getRepository("CadolesCoreBundle:User")->findOneBy(["username"=>"admin"]);
if($groupowner) {
// On recherche le propriétaire du groupe dans only
$respuser = \Unirest\Request::get($this->only_url.'/people/'.$groupowner->getUsername(),$headers);
// Là normalement on a forcement une réponse positive
if(!$this->koresponse($respuser)) {
// Le groupe a un identifiant only, on le recherche via cet ID
if($group->getIdonlyoffice()) {
// On recherche le groupe dans only
$respgroup = \Unirest\Request::get($this->only_url.'/project/'.$group->getIdonlyoffice(),$headers);
// Si le projet existe
if(!$this->koresponse($respgroup)) {
// On regarde s'il y a des changement
if($respgroup->body->response->responsible->userName!=$groupowner->getUsername()||$respgroup->body->response->status!=0||$respgroup->body->response->title!=$grouptitle||$respgroup->body->response->description!=$groupdescription||$respgroup->body->response->isPrivate!=$groupisprivate) {
$this->writeln("Modification du groupe dans Only. Group = ".$group->getLabel());
if(!$simulate) {
// Liste des membres Only
$membersOnly=[];
$respmember = \Unirest\Request::get($this->only_url.'/project/'.$group->getIdonlyoffice().'/team',$headers);
if($this->koresponse($respmember)) {
$this->writelnred("ERREUR SUR RECUPERATION DES MEMBRES du Group = ".$group->getLabel());
continue;
}
foreach($respmember->body->response as $member) {
array_push($membersOnly,$member->id);
}
// On modifie le groupe only
$query = array(
'status' => 0,
'title' => $grouptitle,
'description' => $groupdescription,
'responsibleId' => $respuser->body->response->id,
'participants' => $membersOnly,
'private' => $groupisprivate,
'notify' => true
);
$body = \Unirest\Request\Body::json($query);
$respmodif = \Unirest\Request::put($this->only_url.'/project/'.$respgroup->body->response->id,$headers,$body);
if($this->koresponse($respmodif)) {
$this->writelnred("ERREUR SUR MODIFICATION du Group = ".$group->getLabel());
}
}
}
}
// Sinon c'est qu'il a été supprimé via only : il faut donc le regénérer
else {
$tocreate=true;
}
}
// Sinon c'est que l'on doit le créer dans Only
else {
$tocreate=true;
}
// Création
if($tocreate) {
$this->writeln("Création du groupe dans Only. Group = ".$group->getLabel());
if(!$simulate) {
$query = array(
'title' => $grouptitle,
'description' => $groupdescription,
'responsibleId' => $respuser->body->response->id,
'private' => $groupisprivate,
'notify' => true
);
$body = \Unirest\Request\Body::json($query);
$respsubmit = \Unirest\Request::post($this->only_url.'/project/withSecurity',$headers,$body);
if($this->koresponse($respsubmit)) {
$this->writelnred("ERREUR SUR CREATION du Group = ".$group->getLabel());
}
else {
$group->setIdonlyoffice($respsubmit->body->response->id);
$this->em->persist($group);
$this->em->flush();
}
}
}
}
}
}
$this->writeln('');
$this->writeln('== RATTACHER LES UTILISATEURS =======================');
$groups=$this->em->getRepository("CadolesCoreBundle:Group")->findBy(["fgcanshare"=>true]);
foreach($groups as $group) {
// Si pas d'erreur on doit avoir à présent le projet dans only rattaché à un groupe ninegate
// On va pouvoir s'occuper des membres du groupes
if($group->getIdonlyoffice()) {
// Liste des membres Ninegate
$membersNingate=[];
$usergroups=$this->em->getRepository("CadolesCoreBundle:UserGroup")->findBy(["group"=>$group]);
foreach($usergroups as $member) {
array_push($membersNingate,$member->getUser()->getUsername());
}
// Si groupe sans propriétaire on ajoute forcement admin à la liste des membres du groupe
if(!$group->getOwner()) {
array_push($membersNingate,"admin");
}
// Liste des membres Only
$membersOnly=[];
$respmember = \Unirest\Request::get($this->only_url.'/project/'.$group->getIdonlyoffice().'/team',$headers);
if($this->koresponse($respmember)) {
$this->writelnred("ERREUR SUR RECUPERATION DES MEMBRES du Group = ".$group->getLabel());
continue;
}
foreach($respmember->body->response as $member) {
array_push($membersOnly,$member->userName);
}
// On vérifie que chq membre Ninegate sont dans les membres Only et si pas le cas on le rattache
foreach($membersNingate as $member) {
if(!in_array($member,$membersOnly)) {
$this->writeln("Rattachement au groupe ".$group->getLabel()." l'utilisateur ".$member);
if(!$simulate) {
$respuser = \Unirest\Request::get($this->only_url.'/people/'.$member,$headers);
if($this->koresponse($respuser)) {
$this->writelnred("ERREUR Utilisateur inexistant dans only = ".$member);
}
else {
$query = array('userId' => $respuser->body->response->id);
$body = \Unirest\Request\Body::json($query);
$respsubmit = \Unirest\Request::post($this->only_url.'/project/'.$group->getIdonlyoffice().'/team',$headers,$body);
if($this->koresponse($respsubmit)) {
$this->writelnred("ERREUR SUR RATACHEMENT");
}
}
}
}
}
// On vérifie que chq membre Ninegate sont dans les membres Only et si pas le cas on le rattache
foreach($membersOnly as $member) {
if(!in_array($member,$membersNingate)) {
$this->writeln("Detachement au groupe ".$group->getLabel()." l'utilisateur ".$member);
if(!$simulate) {
$respuser = \Unirest\Request::get($this->only_url.'/people/'.$member,$headers);
if($this->koresponse($respuser)) {
$this->writelnred("ERREUR Utilisateur inexistant dans only = ".$member);
}
else {
$query = array('userId' => $respuser->body->response->id);
$body = \Unirest\Request\Body::json($query);
$respsubmit = \Unirest\Request::delete($this->only_url.'/project/'.$group->getIdonlyoffice().'/team',$headers,$body);
if($this->koresponse($respsubmit)) {
$this->writelnred("ERREUR SUR DETACHEMENT");
}
}
}
}
}
}
}
$this->writeln('');
$this->writeln('== FERMER LES GROUPES FONCTIONNELS====================');
$groups=$this->em->getRepository("CadolesCoreBundle:Group")->findBy(["fgcanshare"=>false]);
foreach($groups as $group) {
if($group->getIdonlyoffice()) {
$grouptitle=$group->getLabel();
$groupdescription=$group->getDescription();
$groupowner=$group->getOwner();
// Si pas de propriétaire de projet on le rattache à admin
if(!$groupowner)
$groupowner=$this->em->getRepository("CadolesCoreBundle:User")->findOneBy(["username"=>"admin"]);
if($groupowner) {
// On recherche le propriétaire du groupe dans only
$respuser = \Unirest\Request::get($this->only_url.'/people/'.$groupowner->getUsername(),$headers);
if(!$this->koresponse($respuser)) {
$respgroup = \Unirest\Request::get($this->only_url.'/project/'.$group->getIdonlyoffice(),$headers);
if(!$this->koresponse($respgroup)) {
if($respgroup->body->response->status!=1) {
$this->writeln("Fermer le groupe dans Only. Group = ".$group->getLabel());
if(!$simulate) {
// On ferme le projet
$query = array(
'title' => $grouptitle,
'description' => $groupdescription,
'responsibleId' => $respuser->body->response->id,
'participants' => $respgroup->body->response->participants,
'private' => $groupisprivate,
'status' => 1,
'notify' => true
);
$body = \Unirest\Request\Body::json($query);
$respupdate = \Unirest\Request::put($this->only_url.'/project/'.$group->getIdonlyoffice(),$headers,$body);
}
}
}
}
}
}
}
}
$this->writeln('');
return 1;
}
function koresponse($response) {
if($response->code>=Response::HTTP_BAD_REQUEST) {
$this->writelnred("ERREUR ".$response->code);
if(property_exists($response,"body") && property_exists($response->body,"error")) $this->writelnred("ERREUR ".$response->body->error->message);;
return true;
}
return false;
}
private function writelnred($string) {
$this->output->writeln('<fg=red>'.$string.'</>');
$this->filesystem->appendToFile($this->rootlog.'cron.log', $string."\n");
}
private function writeln($string) {
$this->output->writeln($string);
$this->filesystem->appendToFile($this->rootlog.'cron.log', $string."\n");
}
private function addMember($group,$user,$role) {
$key = Uuid::uuid4();
$usergroup=new UserGroup();
$usergroup->setUser($user);
$usergroup->setGroup($group);
$usergroup->setRolegroup($role);
$usergroup->setKeyvalue($key);
$this->em->persist($usergroup);
$this->em->flush();
}
private function ctrlFgcanshare($group,$user,$pagetemplate) {
if($group->getFgcanshare()) {
// On regarde s'il a au moins une page
if($group->getPages()->isEmpty()) {
$page=$this->em->getRepository("CadolesPortalBundle:Page")->clonePage(null,$pagetemplate);
$group->addPage($page);
$page->setName($group->getLabel());
$page->setUser($user);
$this->em->persist($page);
$this->em->persist($group);
$this->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);
$calendar->setUser($user);
$this->em->persist($calendar);
$this->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);
$blog->setUser($user);
$this->em->persist($blog);
$this->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);
$project->setUser($user);
$this->em->persist($project);
$this->em->flush();
}
}
}
}