first commit

This commit is contained in:
2022-12-23 16:27:07 +01:00
commit 7b144bd346
383 changed files with 23723 additions and 0 deletions

0
src/Controller/.gitignore vendored Normal file
View File

View File

@ -0,0 +1,109 @@
<?php
namespace App\Controller;
use App\Form\FolderType;
use App\Form\FileType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use App\Service\SftpService;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
class HomeController extends AbstractController
{
private $sftp;
public function __construct(SftpService $sftp)
{
$this->sftp = $sftp;
$this->sftp->connect();
}
public function home(Request $request)
{
$folder=$request->query->get('folder');
// Crétion de répertoire
$formFolder = $this->createForm(FolderType::class);
$formFolder->handleRequest($request);
if ($formFolder->get('submit')->isClicked() && $formFolder->isValid()) {
$name = $formFolder->get("name")->getData();
$this->sftp->mkdir($folder."/".$name);
}
// Modification de fichier
$formFile = $this->createForm(FileType::class);
$formFile->handleRequest($request);
if ($formFile->get('submit')->isClicked() && $formFile->isValid()) {
$oldname = $formFile->get("oldname")->getData();
$name = $formFile->get("name")->getData();
$this->sftp->rename($folder."/".$oldname,$folder."/".$name);
}
// Lister les fichiers
$ls=$this->sftp->ls($folder);
// Construire l'arbre des répertoires
$tree=[];
$tmpparent=explode("/",$folder);
foreach($tmpparent as $key => $parent) {
$tmp=[
"name"=>($parent==""?"Home":$parent),
"folder"=>($key==0?"":$tree[$key-1]["folder"]."/".$parent)
];
array_push($tree,$tmp);
}
// Browse
return $this->render('Home/home.html.twig', [
'useheader' => true,
'usemenu' => false,
'usesidebar' => false,
'tree' => $tree,
'infolder' => $folder,
'folders' => $ls["folders"],
'files' => $ls["files"],
'formfolder'=>$formFolder->createView(),
'formfile'=>$formFile->createView(),
]);
}
public function download(Request $request)
{
$file=$request->query->get('file');
$tmpfile=$this->sftp->downloadFile($file,"var/tmp/");
if(!$tmpfile) {
throw new \Exception('Erreur de téléchargement');
}
if (str_starts_with(mime_content_type($tmpfile), 'image/') || 'application/pdf' == mime_content_type($tmpfile)) {
$response = new BinaryFileResponse($tmpfile);
$response->headers->set('Content-Type', mime_content_type($tmpfile));
} else {
$response = new BinaryFileResponse($tmpfile);
$response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, basename($tmpfile));
}
return $response;
}
public function upload(Request $request)
{
$folder=$request->query->get('folder');
return $this->render('Home/upload.html.twig', [
'folder' => $folder,
]);
}
public function delete(Request $request)
{
$folder=$request->query->get('folder');
$file=$request->query->get('file');
$this->sftp->deleteFile($file);
return $this->redirectToRoute("app_home",["folder"=>$folder]);
}
}

View File

@ -0,0 +1,17 @@
<?php
namespace App\DataFixtures;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Persistence\ObjectManager;
class AppFixtures extends Fixture
{
public function load(ObjectManager $manager): void
{
// $product = new Product();
// $manager->persist($product);
$manager->flush();
}
}

0
src/Entity/.gitignore vendored Normal file
View File

37
src/Form/FileType.php Normal file
View File

@ -0,0 +1,37 @@
<?php
namespace App\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class FileType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('submit',
SubmitType::class, [
'label' => 'Valider',
'attr' => ['class' => 'btn btn-success mb-5'],
]
);
$builder->add('oldname', HiddenType::class,['mapped' => false]);
$builder->add('name',
TextType::class, [
'mapped' => false,
'label' => 'Nom',
'required' => true,
]
);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
]);
}
}

36
src/Form/FolderType.php Normal file
View File

@ -0,0 +1,36 @@
<?php
namespace App\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class FolderType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('submit',
SubmitType::class, [
'label' => 'Valider',
'attr' => ['class' => 'btn btn-success mb-5'],
]
);
$builder->add('name',
TextType::class, [
'mapped' => false,
'label' => 'Nom',
'required' => true,
]
);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
]);
}
}

11
src/Kernel.php Normal file
View File

@ -0,0 +1,11 @@
<?php
namespace App;
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Component\HttpKernel\Kernel as BaseKernel;
class Kernel extends BaseKernel
{
use MicroKernelTrait;
}

0
src/Repository/.gitignore vendored Normal file
View File

174
src/Service/SftpService.php Normal file
View File

@ -0,0 +1,174 @@
<?php
namespace App\Service;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Filesystem\Filesystem;
class SftpService
{
private $rootPath;
private $host;
private $port;
private $user;
private $password;
private $folder;
private $connection = null;
private $sftp = null;
public function __construct($rootPath,ContainerInterface $container)
{
$this->rootPath = $rootPath;
$this->host = $container->getParameter('sftpHost');
$this->port = $container->getParameter('sftpPort');
$this->user = $container->getParameter('sftpUser');
$this->password = $container->getParameter('sftpPassword');
$this->folder = $container->getParameter('sftpFolder');
if(!empty($this->folder)) $this->folder=$this->folder."/";
}
public function connect()
{
if (!$this->connection || !$this->sftp) {
$connection = @ssh2_connect($this->host, $this->port);
if (!$connection) {
throw new \Exception(sprintf('Could not connect to %s on port %s.', $this->host, $this->port));
} else {
if (!@ssh2_auth_password($connection, $this->user, $this->password)) {
throw new \Exception(sprintf('Could not authenticate with username %s ', $this->user));
} else {
$sftp = @ssh2_sftp($connection);
if (!$sftp) {
throw new \Exception('Could not initialize SFTP subsystem.');
} else {
$this->connection = $connection;
$this->sftp = $sftp;
return $this->connection;
}
}
}
} else {
return $this->connection;
}
}
public function disconnect()
{
if ($this->connection) {
ssh2_exec($this->connection, 'exit;');
unset($this->connection);
}
}
public function uploadFile($localFile, $remoteFolder)
{
$remoteFolder=substr($remoteFolder, 1);
$baseName=basename($localFile);
$sftp = $this->sftp;
$remotePath = 'ssh2.sftp://'.join(DIRECTORY_SEPARATOR, [$sftp, $this->folder.$remoteFolder."/".$baseName]);
echo($remotePath);
$stream = @fopen($remotePath, 'w');
if (!$stream) {
echo "here";
return false;
}
$localStream = fopen($localFile, 'r');
while ($chunk = fread($localStream, 8192)) {
fwrite($stream, $chunk);
}
@fclose($localStream);
@fclose($stream);
return true;
}
public function downloadFile($remoteFile)
{
// On enlève le premier /
$remoteFile=substr($remoteFile, 1);
$baseName=basename($remoteFile);
// Construire le nom du fichier local
$localFile=$this->rootPath."/var/tmp/".$baseName;
// Générer le répertoire temporaire de téléchargement
$filesystem = new Filesystem();
$filesystem->mkdir($this->rootPath."/var/tmp");
// Télécharger le fichier
$sftp = $this->sftp;
$remotePath = 'ssh2.sftp://'.join(DIRECTORY_SEPARATOR, [intval($sftp), $this->folder.$remoteFile]);
$remoteFilesize = filesize($remotePath);
$stream = @fopen($remotePath, 'r');
if (!$stream) {
return false;
}
else {
$localStream = fopen($localFile, 'w');
while ($chunk = fread($stream, 8192)) {
fwrite($localStream, $chunk);
}
@fclose($localStream);
}
@fclose($stream);
// Controler que le fichier est correcte
$localFilesize = filesize($localFile);
if ($remoteFilesize !== $localFilesize) {
return false;
}
return $localFile;
}
public function deleteFile($remoteFile)
{
$sftp = $this->sftp;
$remotePath = 'ssh2.sftp://'.join(DIRECTORY_SEPARATOR, [$sftp, $this->folder.$remoteFile]);
rmdir($remotePath);
unlink($remotePath);
return true;
}
public function ls($remoteDir, $filter = '*')
{
$sftp = $this->sftp;
$dir = 'ssh2.sftp://'.join(DIRECTORY_SEPARATOR, [$sftp, $this->folder.$remoteDir]);
$return = [];
$return["folders"] = [];
$return["files"] = [];
$handle = opendir($dir);
if (!$handle) {
throw new \Exception(sprintf('Cannot access remote directory "%s" !', $this->folder.$remoteDir));
}
while (false !== ($file = readdir($handle))) {
if ('.' != substr("$file", 0, 1)) {
if (is_dir(join(DIRECTORY_SEPARATOR, [$dir, $file]))) {
array_push($return["folders"],$file);
} elseif (fnmatch($filter, $file)) {
array_push($return["files"],$file);
}
}
}
closedir($handle);
return $return;
}
public function mkdir($remoteDir)
{
return ssh2_sftp_mkdir($this->sftp, $this->folder.$remoteDir, 0777, true);
}
public function rename($oldFile,$newFile)
{
return ssh2_sftp_rename($this->sftp, $this->folder.$oldFile, $this->folder.$newFile);
}
}

View File

@ -0,0 +1,46 @@
<?php
namespace App\Service;
use Oneup\UploaderBundle\Event\PostPersistEvent;
use Ramsey\Uuid\Uuid;
use Psr\Log\LoggerInterface;
class UploadListener
{
private $sftp;
private $log;
public function __construct(SftpService $sftp, LoggerInterface $log)
{
$this->sftp = $sftp;
$this->log = $log;
}
public function onUpload(PostPersistEvent $event)
{
$type = $event->getType();
switch ($type) {
case 'sftp':
$this->log->debug("IN UPLOAD SFTP");
$request = $event->getRequest();
$folder = $request->get('folder');
$this->log->debug("Folder = ".$folder);
$file = $event->getFile();
$filename = $file->getFilename();
$this->log->debug("File = ".$file);
$response = $event->getResponse();
$response['file'] =$folder.'/'.$filename;
$response['filename'] = $filename;
$this->sftp->connect();
$return=$this->sftp->uploadFile($file, $folder);
if(!$return) throw new \Exception("Upload error");
break;
}
}
}

View File

@ -0,0 +1,14 @@
<?php
namespace App\Service;
use Oneup\UploaderBundle\Uploader\File\FileInterface;
use Oneup\UploaderBundle\Uploader\Naming\NamerInterface;
class UploadSamename implements NamerInterface
{
public function name(FileInterface $file)
{
return $file->getClientOriginalName();
}
}