<?php
namespace App\Controller;
use DateTime;
use App\Entity\Images;
use App\Service\Securizer;
use App\Library\GraphOneDrive;
use App\Repository\ImagesRepository;
use Microsoft\Graph\Model\DriveItem;
use App\Repository\ClientsRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Serializer\SerializerInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface;
class ImagesController extends AbstractController
{
/**
* @IsGranted("ROLE_TECH")
*/
public function index(int $id, ImagesRepository $repoImages, ClientsRepository $repoClient, EntityManagerInterface $manager): Response
{
// Synchronisation et récupération des images d'un client
$graph = new GraphOneDrive();
$client = $repoClient->find($id);
$images = $repoImages->findBy(['idClient' => $id]);
$idDrive = "b!0B8l_7Yi_U2bP-TRWI8AGy-WjI76ekZLrXGgrRJbi4d9LH8_adGXT6XMhZMdfqIi";
$filesOneDrive = $graph->listContentFolder($idDrive, $client->getGraphFolderId());
if (isset($filesOneDrive)) {
// S'il y a de nouvelles images, ajoutez-les
$addedImages = array_filter($filesOneDrive, function (DriveItem $file) use ($images) {
if ($file->getFile() == null) return false;
if ($file->getFile()->getMimeType() != "image/jpeg" && $file->getFile()->getMimeType() != "image/jpg" && $file->getFile()->getMimeType() != "image/png") return false;
foreach ($images as $img) {
if ($file->getId() === $img->getDriveId()) return false;
}
return true;
});
foreach ($addedImages as $add) {
$entity = new Images();
$today = new DateTime();
$entity->setIdClient($client)
->setUploadedDate($today)
->setDriveId($add->getId());
$manager->persist($entity);
}
// Les images supprimées dans Onedrive, supprimez-les dans l'extranet aussi
$deletedImages = array_filter($images, function (Images $img) use ($filesOneDrive) {
foreach ($filesOneDrive as $file) {
if ($file->getId() === $img->getDriveId()) return false;
}
return true;
});
foreach ($deletedImages as $image) {
$repoImages->remove($image, true);
}
$manager->flush();
}
$images = $repoImages->findBy(['idClient' => $id]);
return $this->json($images, 200, [], ['groups' => 'affichageImage']);
}
public function upload(Request $request, EntityManagerInterface $manager, ClientsRepository $repoClient, AccessDecisionManagerInterface $accessDecisionManager): Response
{
$securizer = new Securizer($accessDecisionManager);
if (!$securizer->isGranted($this->getUser(), "ROLE_TECH"))
return $this->json([
'status' => 400,
'message' => "Vous ne pouvez pas consulter cet élément"
], 400);
try {
$file = $request->files->get('myFile');
$graphOneDrive = new GraphOneDrive();
$client = $repoClient->find($_POST["idClient"]);
$folderGraphId = $client->getGraphFolderId();
if (!isset($folderGraphId)) {
return $this->json([
'status' => 400,
'message' => "There isn't a graph folder id for the selected client"
], 400);
}
$path = dirname(__DIR__) . '/../documents/images/';
if (!is_dir($path))
mkdir($path, 0777, true);
$fileName = $_FILES["myFile"]["name"];
// ** Télécharger le fichier
if (!empty($file)) {
$file->move(
$path,
$fileName
);
}
$path = $path . $fileName;
$filesize = filesize($path);
$fp = fopen($path, 'rb');
$binary = fread($fp, $filesize);
fclose($fp);
$idDrive = "b!0B8l_7Yi_U2bP-TRWI8AGy-WjI76ekZLrXGgrRJbi4d9LH8_adGXT6XMhZMdfqIi";
$fileAdded = $graphOneDrive->uploadFile($idDrive, $folderGraphId, $fileName, $binary);
$entity = new Images();
$today = new DateTime();
$entity->setIdClient($client)->setUploadedDate($today)->setDriveId($fileAdded->getId());
$manager->persist($entity);
$manager->flush();
unlink($path);
} catch (\throwable $e) {
return $this->json([
'status' => 400,
'message' => $e->getMessage()
], 400);
}
return $this->json($entity, 201, [], ['groups' => 'affichageElement']);
}
/**
* @IsGranted("ROLE_TECH")
*/
public function modif($id, Request $request, ImagesRepository $repoImages, AccessDecisionManagerInterface $accessDecisionManager, EntityManagerInterface $manager, SerializerInterface $serializer): Response
{
//permets de effacer une image d'un client, seul les roles TECH et supperieur peuvent acceder a cette url
$securizer = new Securizer($accessDecisionManager);
if ($securizer->isGranted($this->getUser(), "ROLE_TECH")) {
$image = $repoImages->find($id);
$jsonRecu = $request->getContent();
//transforme le json reçu en entity
$serializer->deserialize($jsonRecu, Images::class, 'json', ['object_to_populate' => $image]);
$manager->persist($image);
$manager->flush();
} else {
return $this->json([
'status' => 400,
'message' => "Vous ne pouvez pas modifier cet élément"
], 400);
}
return $this->json(true, 200, []);
}
/**
* @IsGranted("ROLE_TECH")
*/
public function delete($id, ImagesRepository $repoImages, AccessDecisionManagerInterface $accessDecisionManager): Response
{
//permets de effacer une image d'un client, seul les roles TECH et supperieur peuvent acceder a cette url
$securizer = new Securizer($accessDecisionManager);
if ($securizer->isGranted($this->getUser(), "ROLE_TECH")) {
// recuperer id de sharepoint
$image = $repoImages->find($id);
// faire delete image en sharepoint
$graphOneDrive = new GraphOneDrive();
$idDrive = "b!0B8l_7Yi_U2bP-TRWI8AGy-WjI76ekZLrXGgrRJbi4d9LH8_adGXT6XMhZMdfqIi";
$graphOneDrive->deleteFile($idDrive, $image->getDriveId());
// si ça marche bine supprimer l'entity
$repoImages->remove($image, true);
} else {
return $this->json([
'status' => 400,
'message' => "Vous ne pouvez pas consulter cet élément"
], 400);
}
return $this->json(true, 200, [], ['groups' => 'affichageImage']);
}
/**
* @IsGranted("ROLE_TECH")
*/
public function getBase64Image($id)
{
$idDrive = "b!0B8l_7Yi_U2bP-TRWI8AGy-WjI76ekZLrXGgrRJbi4d9LH8_adGXT6XMhZMdfqIi";
$graph = new GraphOneDrive();
$item = $graph->getFolderDrive($idDrive, $id);
$path = $item->getProperties()['@microsoft.graph.downloadUrl'];
$context = stream_context_create(array('http' => array('header' => 'Connection: close\r\n')));
header('Expires: '.gmdate('D, d M Y H:i:s \G\M\T', time() + (60 * 60 * 24)));
readfile($path, false, $context);
}
/**
* @IsGranted("ROLE_ADMIN")
*/
public function listFoldersClients($idFolder, AccessDecisionManagerInterface $accessDecisionManager): Response
{
$securizer = new Securizer($accessDecisionManager);
if (!$securizer->isGranted($this->getUser(), "ROLE_ADMIN"))
return $this->json([
'status' => 400,
'message' => "Vous ne pouvez pas consulter cet élément"
], 400);
$graphOneDrive = new GraphOneDrive();
if ($idFolder == "null")
$data = $graphOneDrive->listFolderDrive("b!0B8l_7Yi_U2bP-TRWI8AGy-WjI76ekZLrXGgrRJbi4d9LH8_adGXT6XMhZMdfqIi");
else
$data = $graphOneDrive->listContentFolder("b!0B8l_7Yi_U2bP-TRWI8AGy-WjI76ekZLrXGgrRJbi4d9LH8_adGXT6XMhZMdfqIi", $idFolder);
return $this->json($data, 200, []);
}
}