Update NPM deps and webpack.mix.js

composer require ldc/web-status-checker-laravel remove Old static status checker

Fix ImportMedia

WIP commands OK

many fixes

Fix and try to optimize folder component

Fix front icons + actions based on icons

Favico

front fix alert

Fix Media upload on depot

fix folder component buttons

Full front fix with perf due tu vuejs

Download medias

Navigate within medias superfix

Move media + loader

isLocked boolean and remove media fix

Folder scroll fix

arcadia link color red

Fix panier show external

Tons of fixes back as front

REwrited all
This commit is contained in:
Jérémy Munsch 2022-06-20 14:57:58 +02:00
parent bb38b9e400
commit 9767e62c72
No known key found for this signature in database
GPG key ID: 18361AF3BFEC0FEC
233 changed files with 18637 additions and 16231 deletions

View file

@ -1,4 +1,9 @@
# DAM
# TODO:
- Remplace par VUE 3 + Runtime Only
- Typescript
## Installation
### - Default
```
@ -34,4 +39,4 @@ php artisan key:generate
## Dans les LABs
```
MAIL_VERIFY_PEER=false
```
```

View file

@ -19,7 +19,7 @@ class ArcadiaLinkCommand extends Command
*
* @var string
*/
protected $description = 'Lecture du flux Arcadia entrant (medias). Run the XmlArcadiaMediasIn manually';
protected $description = 'Lecture du flux Arcadia entrant (media). Run the XmlArcadiaMediasIn manually';
/**
* Execute the console command.
@ -34,7 +34,7 @@ class ArcadiaLinkCommand extends Command
$job->console = $this;
$job->handle();
$this->line("");
$this->newLine();
$this->info('Fin du traitement');
}
}

View file

@ -5,8 +5,6 @@ namespace App\Console\Commands;
use App\Models\Media;
use App\Models\Sujet;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
class DeleteMediaArchive extends Command
{
@ -15,7 +13,7 @@ class DeleteMediaArchive extends Command
*
* @var string
*/
protected $signature = 'medias:deletearchive';
protected $signature = 'media:deletearchive';
/**
* The console command description.
@ -35,75 +33,59 @@ class DeleteMediaArchive extends Command
//phpcs:ignore Generic.Files.LineLength.TooLong
$this->info('Vous allez supprimer définitivement tous les médias (et leurs fichiers) qui ont été supprimés (en soft delete).');
$choice = $this->choice('Etes-vous sûr de vouloir lancer ce traitement ?', ['y', 'n'], 'y');
if ($choice != "y") {
$this->error('Choix incorrect');
die();
if (!$this->confirm('Etes-vous sûr de vouloir lancer ce traitement ?')) {
return 0;
}
$sujets = Sujet::where('sujet_dam', 1)->get();
/** @var \Illuminate\Database\Eloquent\Collection<\App\Models\Sujet> */
$subjects = Sujet::where('sujet_dam', true)->get();
$this->line("");
$this->line("Liste des sujets disponibles");
$this->line("----------------------------");
foreach ($sujets as $key => $sujet) {
$this->line("[" . $sujet->codeSujet . "] " . $sujet->libelle);
$this->newLine();
$this->line('Liste des sujets disponibles');
$this->line('----------------------------');
$this->line('[0] Tous les sujets');
foreach ($subjects as $subject) {
$this->line("[{$subject->codeSujet}] {$subject->libelle}");
}
$this->line("[0] Tous les sujets");
$sujetId = $this->ask('Pour quel sujet de média souhaitez vous executer le traitement ?');
$sujetId = $this->askWithCompletion(
'Pour quel sujet de média souhaitez vous executer le traitement ?',
$subjects->pluck('codeSujet')->toArray(),
0
);
if ($sujetId == "") {
$this->newLine();
if ($sujetId != 0 and !$subjects->pluck('codeSujet')->contains(\intval($sujetId))) {
$this->error('Id de sujet incorrect');
die();
return -1;
}
if ($sujetId == 0) {
$medias = Media::onlyTrashed()->with('Sujet.formats')->get();
} else {
$medias = Media::onlyTrashed()->where('sujet_id', $sujetId)->with('Sujet.formats')->get();
}
$sujetId = intval($sujetId);
if ($medias->count() == 0) {
$mediaCollection = Media::onlyTrashed()->with('sujet.formats');
if ($sujetId !== 0) {
$mediaCollection->where('sujet_id', $sujetId);
}
/** @var \Illuminate\Database\Eloquent\Collection<\App\Models\Media> */
$mediaCollection = $mediaCollection->get();
if (!$mediaCollection->count()) {
$this->error('Aucun média a supprimer');
die();
return -1;
}
$this->info($medias->count() . ' média(s) trouvé(s) - Début du traitement');
$bar = $this->output->createProgressBar(count($medias));
$this->info($mediaCollection->count() . ' média(s) trouvé(s) - Début du traitement');
$bar = $this->output->createProgressBar($mediaCollection->count());
$bar->start();
foreach ($medias as $media) {
// * supprime les fichiers médias stockés sur disque
$files = Storage::files($media->folder . "/");
$filepath = preg_quote($media->folder . $media->uid, '/');
$matchingFiles = preg_grep('/^' . $filepath . '/', $files);
if (\is_array($matchingFiles)) {
$this->deleteFiles($matchingFiles);
}
// * supprime le media en bdd
$media->forceDelete();
foreach ($mediaCollection as $media) {
$media->prune();
$bar->advance();
}
$bar->finish();
$this->line("");
$this->newLine();
$this->info('Fin du traitement');
}
/**
* Delete files
*
* @param array $files
* @return void
*/
private function deleteFiles(array $files)
{
collect($files)->map(function (string $filename) {
if (!Storage::delete($filename)) {
Log::warning("Could not delete $filename from storage.");
}
});
}
}

View file

@ -2,23 +2,23 @@
namespace App\Console\Commands;
use App\Http\Traits\MediaTools;
use App\Traits\Http\HandlesMedia;
use App\Models\Article;
use App\Models\Marque;
use App\Models\Site;
use App\Models\Societe;
use App\Models\Sujet;
use App\Models\Typemedia;
use App\Models\Typevue;
use App\Models\TypeMedia;
use App\Models\TypeVue;
use App\Models\Variante;
use Illuminate\Console\Command;
use Illuminate\Contracts\Filesystem\FileNotFoundException;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use League\Flysystem\FileNotFoundException;
class ImportArcadiaFiles extends Command
class ImportArcadiaModelFiles extends Command
{
use MediaTools;
use HandlesMedia;
/**
* The name and signature of the console command.
@ -32,7 +32,7 @@ class ImportArcadiaFiles extends Command
*
* @var string
*/
protected $description = 'Import des fichiers xml Arcadia';
protected $description = 'Import des modèles xml Arcadia';
/**
* Execute the console command.
@ -44,17 +44,24 @@ class ImportArcadiaFiles extends Command
*/
public function handle()
{
/** @var \Illuminate\Support\Collection<string> */
$files = collect(Storage::disk('arcadia')->files())
->filter(function (string $fileName) {
return !\in_array($fileName, ['.gitignore']);
});
if (!$files->count()) {
$this->info('Pas de nouveau fichiers');
return 0;
}
$this->info('Démarrage du traitement');
$files = collect(Storage::disk('arcadia')->files());
$bar = $this->output->createProgressBar(count($files) - 1);
$bar = $this->output->createProgressBar($files->count() - 1);
$bar->start();
// ---- Pour chaque fichier
foreach ($files as $filename) {
if ($filename == ".gitignore") {
continue;
}
// ---- Récupération du contenu
if (!($fileContent = Storage::disk('arcadia')->get($filename))) {
throw new FileNotFoundException($filename);
@ -104,7 +111,7 @@ class ImportArcadiaFiles extends Command
} //end foreach
$bar->finish();
$this->line("");
$this->newLine();
$this->info('Fin du traitement');
}
@ -121,33 +128,20 @@ class ImportArcadiaFiles extends Command
foreach ($fileContent->dam as $row) {
/** @var \App\Models\Article|null $record */
$record = Article::where('noArt', $row->noArt)->first();
if ($record) {
// * Update record
$record->libCcial = $row->libCcial;
$record->codMarq = $row->codMarq;
$record->libMarq = $row->libMarq;
$record->codFamVte = $row->codFamVte;
$record->libFamVte = $row->libFamVte;
$record->codGencodAdm = $row->codGencodAdm;
$record->codGencodSymb = $row->codGencodSymb;
$record->codGencodPds = $row->codGencodPds;
$record->utilisableGroupe = $row->utilisableGroupe;
$record->saveOrFail();
} else {
// * Insert new record
$record = new Article();
$record->noArt = $row->noArt;
$record->libCcial = $row->libCcial;
$record->codMarq = $row->codMarq;
$record->libMarq = $row->libMarq;
$record->codFamVte = $row->codFamVte;
$record->libFamVte = $row->libFamVte;
$record->codGencodAdm = $row->codGencodAdm;
$record->codGencodSymb = $row->codGencodSymb;
$record->codGencodPds = $row->codGencodPds;
$record->utilisableGroupe = $row->utilisableGroupe;
$record->saveOrFail();
} //end if
if (!$record) {
$record = new Article();
$record->noArt = $row->noArt;
}
$record->libCcial = $row->libCcial;
$record->codMarq = $row->codMarq;
$record->libMarq = $row->libMarq;
$record->codFamVte = $row->codFamVte;
$record->libFamVte = $row->libFamVte;
$record->codGencodAdm = $row->codGencodAdm;
$record->codGencodSymb = $row->codGencodSymb;
$record->codGencodPds = $row->codGencodPds;
$record->utilisableGroupe = $row->utilisableGroupe;
$record->saveOrFail();
} //end foreach
}
@ -164,17 +158,12 @@ class ImportArcadiaFiles extends Command
foreach ($fileContent->dam as $row) {
/** @var \App\Models\Marque|null $record */
$record = Marque::where('codMarq', $row->codMarq)->first();
if ($record) {
// * Update record
$record->libMarq = $row->libMarq;
$record->saveOrFail();
} else {
// * Insert new record
if (!$record) {
$record = new Marque();
$record->codMarq = $row->codMarq;
$record->libMarq = $row->libMarq;
$record->saveOrFail();
}
$record->libMarq = $row->libMarq;
$record->saveOrFail();
}
}
@ -191,17 +180,12 @@ class ImportArcadiaFiles extends Command
foreach ($fileContent->mediaSujet as $row) {
/** @var \App\Models\Sujet|null $record */
$record = Sujet::where('codeSujet', $row->code)->first();
if ($record) {
// * Update record
$record->libelle = $row->libelle;
$record->saveOrFail();
} else {
// * Insert new record
if (!$record) {
$record = new Sujet();
$record->codeSujet = $row->code;
$record->libelle = $row->libelle;
$record->saveOrFail();
}
$record->libelle = $row->libelle;
$record->saveOrFail();
}
}
@ -216,19 +200,14 @@ class ImportArcadiaFiles extends Command
{
/** @var \SimpleXMLElement $row */
foreach ($fileContent->mediatypemedia as $row) {
/** @var \App\Models\Typemedia|null $record */
$record = Typemedia::where('codeTypemedia', $row->code)->first();
if ($record) {
// * Update record
$record->libelle = $row->libelle;
$record->saveOrFail();
} else {
// * Insert new record
$record = new Typemedia();
/** @var \App\Models\TypeMedia|null $record */
$record = TypeMedia::where('codeTypemedia', $row->code)->first();
if (!$record) {
$record = new TypeMedia();
$record->codeTypemedia = $row->code;
$record->libelle = $row->libelle;
$record->saveOrFail();
}
$record->libelle = $row->libelle;
$record->saveOrFail();
}
}
@ -243,21 +222,15 @@ class ImportArcadiaFiles extends Command
{
/** @var \SimpleXMLElement $row */
foreach ($fileContent->mediatypesvue as $row) {
/** @var \App\Models\Typevue|null $record */
$record = Typevue::where('codeTypevue', $row->code)->first();
if ($record) {
// * Update record
$record->libelle = $row->libelle;
$record->sujet_id = $row->sujet_id->mediasujet->code;
$record->saveOrFail();
} else {
// * Insert new record
$record = new Typevue();
/** @var \App\Models\TypeVue|null $record */
$record = TypeVue::where('codeTypevue', $row->code)->first();
if (!$record) {
$record = new TypeVue();
$record->codeTypevue = $row->code;
$record->libelle = $row->libelle;
$record->sujet_id = $row->sujet_id->mediasujet->code;
$record->saveOrFail();
}
$record->libelle = $row->libelle;
$record->sujet_id = $row->sujet_id->mediasujet->code;
$record->saveOrFail();
}
}
@ -272,23 +245,16 @@ class ImportArcadiaFiles extends Command
{
/** @var \SimpleXMLElement $row */
foreach ($fileContent->mediavariante as $row) {
/** @var \App\Models\Typevue|null $record */
/** @var \App\Models\TypeVue|null $record */
$record = Variante::where('codeVariante', $row->code)->first();
if ($record) {
// * Update record
$record->libelle = $row->libelle;
$record->sujet_id = $row->sujet_id->children()[0]->code;
$record->typevue_id = $row->CodeTypeVue->mediatypesvue->code;
$record->saveOrFail();
} else {
// * Insert new record
if (!$record) {
$record = new Variante();
$record->codeVariante = $row->code;
$record->libelle = $row->libelle;
$record->sujet_id = $row->sujet_id->children()[0]->code;
$record->typevue_id = $row->CodeTypeVue->mediatypesvue->code;
$record->saveOrFail();
}
$record->libelle = $row->libelle;
$record->sujet_id = $row->sujet_id->children()[0]->code;
$record->type_vue_id = $row->CodeTypeVue->mediatypesvue->code;
$record->saveOrFail();
}
}
@ -303,19 +269,14 @@ class ImportArcadiaFiles extends Command
{
/** @var \SimpleXMLElement $row */
foreach ($fileContent->SITE_PROD_GRP as $row) {
/** @var \App\Models\Typevue|null $record */
/** @var \App\Models\TypeVue|null $record */
$record = Site::where('id', $row->code)->first();
if ($record) {
// * Update record
$record->libelle = $row->libelle;
$record->saveOrFail();
} else {
// * Insert new record
$record = new Site();
$record->id = $row->code;
$record->libelle = $row->libelle;
$record->saveOrFail();
if (!$record) {
$record = new Site();
$record->id = $row->code;
}
$record->libelle = $row->libelle;
$record->saveOrFail();
}
}
@ -330,19 +291,14 @@ class ImportArcadiaFiles extends Command
{
/** @var \SimpleXMLElement $row */
foreach ($fileContent->dam as $row) {
/** @var \App\Models\Typevue|null $record */
/** @var \App\Models\TypeVue|null $record */
$record = Societe::where('id', $row->codSociete)->first();
if ($record) {
// * Update record
$record->libelle = $row->nomSociete;
$record->saveOrFail();
} else {
// * Insert new record
$record = new Societe();
$record->id = $row->codSociete;
$record->libelle = $row->nomSociete;
$record->saveOrFail();
if (!$record) {
$record = new Societe();
$record->id = $row->codSociete;
}
$record->libelle = $row->nomSociete;
$record->saveOrFail();
}
}

View file

@ -1,393 +0,0 @@
<?php
namespace App\Console\Commands;
use App\Http\Traits\MediaTools;
use App\Models\Article;
use App\Models\Dossier;
use App\Models\Marque;
use App\Models\Media;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use League\Flysystem\FileNotFoundException;
class ImportMedia extends Command
{
use MediaTools;
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'medias:import';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Import des fichiers xml Média Visuel Arcadia';
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$this->info('Démarrage du traitement');
$files = File::glob(storage_path('export_arcadia') . '/DAM_MEDIA_VISUEL_*.*');
$this->line("-> Import du fichier DAM_MEDIA_VISUEL");
$this->xmlVisuels($files);
$this->associateMediasArticles($files);
$this->associateMediasMarques($files);
$this->associateMediasSocietes($files);
$this->line("");
$this->info('Fin du traitement');
}
/**
* Traitement de l'association media <-> societe
*
* @param array $files
* @return void
* @throws \ErrorException If a xml file could not be parsed.
* @throws \League\Flysystem\FileNotFoundException If a file could not be read.
*/
private function associateMediasSocietes(array $files): void
{
$files = File::glob(storage_path('export_arcadia') . "/DAM_ASSO_SOCIETE_*.*");
$this->line("-> Import du fichier DAM_ASSO_SOCIETE");
foreach ($files as $filename) {
$path = explode("/", $filename);
$filename = $path[count($path) - 1];
// ---- Récupération du contenu
if (!($oneFile = Storage::disk('arcadia')->get($filename))) {
throw new FileNotFoundException($filename);
}
if (!($fileContent = simplexml_load_string($oneFile))) {
throw new \ErrorException("Could not parse $filename from arcadia storage.");
}
// ---- traitement du fichier
$bar = $this->output->createProgressBar(count($fileContent->mediaassosociete) - 1);
$bar->start();
/** @var \SimpleXMLElement $row */
foreach ($fileContent->mediaassosociete as $row) {
/** @var \App\Models\Media|null */
$record = Media::where('arcadia_id', $row->codeVisuel)->first();
if ($record) {
// * attache la societe au média
$record->societes()->attach($row->codSociete);
} else {
$this->line("\nDAM_ASSO_SOCIETE : le media n°$row->codeVisuel n'existe pas");
}
$bar->advance();
}
$bar->finish();
$this->deleteFile($filename);
} //end foreach
}
/**
* Traitement de l'association media <-> marque
*
* @param array $files
* @return void
* @throws \ErrorException If a xml file could not be parsed.
* @throws \League\Flysystem\FileNotFoundException If a file could not be read.
*/
private function associateMediasMarques(array $files): void
{
$files = File::glob(storage_path('export_arcadia') . "/DAM_ASSO_MARQUE_*.*");
$this->line("-> Import du fichier DAM_ASSO_MARQUE");
foreach ($files as $filename) {
$path = explode("/", $filename);
$filename = $path[count($path) - 1];
// ---- Récupération du contenu
if (!($oneFile = Storage::disk('arcadia')->get($filename))) {
throw new FileNotFoundException($filename);
}
if (!($fileContent = simplexml_load_string($oneFile))) {
throw new \ErrorException("Could not parse $filename from arcadia storage.");
}
// ---- traitement du fichier
$bar = $this->output->createProgressBar(count($fileContent->mediaassomarque) - 1);
$bar->start();
/** @var \SimpleXMLElement $row */
foreach ($fileContent->mediaassomarque as $row) {
/** @var \App\Models\Media|null */
$record = Media::where('arcadia_id', $row->codeVisuel)->first();
if ($record) {
if ($record->marques->contains($row->codMarq)) {
$this->line("\nDAM_ASSO_MARQUE : le media n°$row->codeVisuel est déjà associé à cette marque.");
} else {
// * attache la marque au média
$record->marques()->attach($row->codMarq);
}
} else {
$this->line("\nDAM_ASSO_MARQUE : le media n°$row->codeVisuel n'existe pas");
}
$bar->advance();
}
$bar->finish();
$this->deleteFile($filename);
} //end foreach
}
/**
* Traitement de l'association media <-> article
*
* @param array $files
* @return void
* @throws \ErrorException If a xml file could not be parsed.
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException If a model cant be found on transaction.
* @throws \League\Flysystem\FileNotFoundException If a file could not be read.
* @throws \Throwable If saving fails.
* @phpcs:disable Generic.Metrics.NestingLevel.TooHigh
* @phpcs:disable Squiz.Commenting.FunctionCommentThrowTag.WrongNumber
*/
private function associateMediasArticles(array $files): void
{
$files = File::glob(storage_path('export_arcadia') . "/DAM_ASSO_ARTICLE_*.*");
$this->line("-> Import du fichier DAM_ASSO_ARTICLE");
/** @var string $filename */
foreach ($files as $filename) {
$path = explode("/", $filename);
$filename = $path[count($path) - 1];
// ---- Récupération du contenu
if (!($oneFile = Storage::disk('arcadia')->get($filename))) {
throw new FileNotFoundException($filename);
}
if (!($fileContent = simplexml_load_string($oneFile))) {
throw new \ErrorException("Could not parse $filename from arcadia storage.");
}
// ---- traitement du fichier
$bar = $this->output->createProgressBar(count($fileContent->mediaassoarticle) - 1);
$bar->start();
/** @var \SimpleXMLElement $row */
foreach ($fileContent->mediaassoarticle as $row) {
/** @var \App\Models\Media|null */
$record = Media::where('arcadia_id', $row->codeVisuel)->first();
if ($record) {
/** @var \App\Models\Article|null */
$article = Article::where('noArt', $row->noArt)->first();
if ($article) {
// * attache l'article au média
$record->articles()->syncWithoutDetaching($article->id);
// * recherche un dossier lié à la marque de l'article
$marque_id = $article->codMarq;
/** @var \App\Models\Dossier|null */
$dossier = Dossier::whereHas("marques", function ($query) use ($marque_id) {
$query->where("codMarq", $marque_id);
})->first();
if ($dossier) {
// * attache le dossier marque au Média
$record->dossier_id = $dossier->id;
$record->save();
$this->line("Liason media n°$row->codeVisuel à la marque n°$article->libMarq");
} else {
DB::transaction(function () use ($record, $marque_id) {
/** @var \App\Models\Marque */
$marque = Marque::where('codMarq', '=', $marque_id)->firstOrFail();
// * On cree le dossier
$dossier = new Dossier();
$dossier->libelle = $marque->libMarq;
$dossier->sujet_id = 1;
$dossier->system = false;
$dossier->saveOrFail();
$dossier->marques()->syncWithoutDetaching($marque_id);
$dossier->saveOrFail();
$record->dossier_id = $dossier->id;
$record->saveOrFail();
});
} //end if
} else {
// phpcs:ignore Generic.Files.LineLength.TooLong
$this->line("\nDAM_ASSO_ARTICLE : le media n°$row->codeVisuel ne peut être lié à l'article n°$row->noArt");
} //end if
} else {
$this->line("\nDAM_ASSO_ARTICLE : le media n°$row->codeVisuel n'existe pas");
} //end if
$bar->advance();
} //end foreach
$bar->finish();
$this->deleteFile($filename);
} //end foreach
}
/**
* Traitement de l'import des XML Visuel
*
* @param array $files
* @return void
* @throws \League\Flysystem\FileNotFoundException If a file could not be read.
* @throws \ErrorException If a xml file could not be parsed.
*/
private function xmlVisuels(array $files): void
{
foreach ($files as $filename) {
$path = explode("/", $filename);
$filename = $path[count($path) - 1];
// ---- Récupération du contenu
if (!($oneFile = Storage::disk('arcadia')->get($filename))) {
throw new FileNotFoundException($filename);
}
if (!($fileContent = simplexml_load_string($oneFile))) {
throw new \ErrorException("Could not parse $filename from arcadia storage.");
}
// ---- traitement du fichier
$bar = $this->output->createProgressBar(count($fileContent->MEDIA_VISUEL) - 1);
$bar->start();
/** @var \SimpleXMLElement $row */
foreach ($fileContent->MEDIA_VISUEL as $row) {
/** @var \App\Models\Media|null */
$record = Media::where('arcadia_id', $row->code)->first();
if (!$record) {
// * Insert new record
$record = new Media();
$record->arcadia_id = $row->code;
if ($row->extension != "") {
$record->extension = $row->extension->typeFichier->libExtension;
}
$record->libelle = $row->libelle;
$record->largeur = $row->nbPxLargeur;
$record->largeur_mm = $row->largeurMm;
$record->hauteur = $row->nbPxHauteur;
$record->hauteur_mm = $row->hauteurMm;
$record->resolution = $row->pppLargeur;
if ($row->version != "") {
$record->version = $row->version;
} else {
$record->version = 1;
}
if ($row->codeTypeMedia != "") {
$record->typemedia_id = $row->codeTypeMedia;
} else {
$record->typemedia_id = 1;
}
if (
$row->codeTypeVue != ""
) {
$record->typevue_id = $row->codeTypeVue;
}
$record->commentaire = $row->commentaire;
$record->sujet_id = $row->codeSujet;
if ($row->langue != "") {
$record->langue_id = $row->langue;
}
if ($row->copyright != "") {
$record->copyright_id = $row->copyright;
} else {
$record->copyright_id = 3;
}
if ($row->codeVariante != "") {
$record->variante_id = $row->codeVariante;
}
if ($row->dateCreation != "") {
$row->dateCreation = substr($row->dateCreation, 0, 10);
$date = explode("/", $row->dateCreation);
$record->created_at = $date[2] . '-' . $date[1] . '-' . $date[0];
}
if ($row->dateModification != "") {
$row->dateModification = substr($row->dateModification, 0, 10);
$date = explode("/", $row->dateModification);
$record->updated_at = $date[2] . '-' . $date[1] . '-' . $date[0];
}
if ($row->datePublication != "") {
$row->datePublication = substr($row->datePublication, 0, 10);
$date = explode("/", $row->datePublication);
$record->published_at = $date[2] . '-' . $date[1] . '-' . $date[0];
}
$record->statut = config('services.statut.public_etendu');
// Affectation d'un dossier et d'un uid.
$destinationPath = $this->getMediaFolder() . "/";
$record->folder = $destinationPath;
$record->uid = Str::uuid();
$mediaFile = "/images/{$record->arcadia_id}.{$record->extension}";
if (Storage::disk('arcadia')->exists($mediaFile)) {
// * déplacement du média et renommage du fichier
if (!($fileContent = Storage::disk('arcadia')->get($mediaFile))) {
throw new \ErrorException("Could not read $mediaFile from arcadia storage.");
}
// * According to config, should throw exception on failure.
Storage::disk('local')->put(
$fileContent,
"{$destinationPath}{$record->uid}.$record->extension"
);
// * calcul de la taille du média
$record->taille = $this->formatBytes(Storage::disk('local')
->size("{$destinationPath}{$record->uid}.$record->extension"));
} else {
// * on applique une image par défaut
$record->extension = "jpg";
Storage::disk('local')->copy(
"assets/images/default.jpg",
"{$destinationPath}{$record->uid}.{$record->extension}"
);
// * calcul de la taille du média
$record->taille = $this->formatBytes(Storage::disk('local')
->size("{$destinationPath}{$record->uid}.{$record->extension}"));
} //end if
$record->saveOrFail();
// ---- Creation des vignettes de base
$this->createSysThumb($record);
// ---- Creation des vignettes en lien avec le sujet du média
$this->createThumb($record);
} else {
$this->line("\nDAM_MEDIA_VISUEL : le media n°$row->code existe déjà en base");
} //end if
$bar->advance();
} //end foreach
$bar->finish();
$this->deleteFile($filename);
} //end foreach
}
/**
* Delete file
*
* @param string $filename
* @return void
*/
private function deleteFile(string $filename): void
{
if (!Storage::disk('arcadia')->delete($filename)) {
Log::warning("Could not delete $filename from arcadia storage.");
}
}
}

View file

@ -1,78 +0,0 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
/**
* Command Name: LDC Web Status Checker
* Description: Envoi des infos Serveur/Laravel vers LDC Web
* Version: 1.1
* Author: Vincent BRIDIER
* Author URI: vincent.bridier@ldc.fr
*
* @codeCoverageIgnore
*/
class LdcWebStatusChecker extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'ldcweb:statuschecker';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Envoi des infos Serveur/Laravel vers LDC Web';
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$data = [];
$data['uuid'] = config('ldcweb.project_uuid');
// Sitemap.xml ?
if (file_exists(public_path() . '/sitemap.xml')) {
$data['sitemap'] = 'true';
} else {
$data['sitemap'] = 'false';
}
// Robots.txt ?
if (file_exists(public_path() . '/robots.txt')) {
$data['robots'] = 'true';
} else {
$data['robots'] = 'false';
}
// Check logs.
$data['logs'] = 0;
$patherror = storage_path('/logs');
$files = glob($patherror . '/*.log');
if (count($files) > 0) {
foreach ($files as $file) {
$data['logs'] = $data['logs'] + filesize($file);
}
}
$data['code']['version'] = app()->version();
// Send by cURL.
$url = 'https://ldc-web.ldc.fr/api/status-checker';
$ch = curl_init($url);
$payload = ['token' => 'CE8S52Qq7stf5k8frF4T', 'datas' => json_encode($data)];
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
curl_close($ch);
return 0;
}
}

View file

@ -2,21 +2,18 @@
namespace App\Console\Commands;
use App\Http\Traits\MediaTools;
use App\Models\Media;
use App\Models\Sujet;
use Illuminate\Console\Command;
class RegenerateThumbnails extends Command
{
use MediaTools;
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'medias:regenerate';
protected $signature = 'media:regenerate';
/**
* The console command description.
@ -34,49 +31,61 @@ class RegenerateThumbnails extends Command
{
$this->info('Vous allez regénérer toutes les miniatures des médias.');
$sujets = Sujet::where('sujet_dam', 1)->get();
/** @var \Illuminate\Database\Eloquent\Collection<\App\Models\Sujet> */
$subjects = Sujet::where('sujet_dam', true)->get();
$this->line("");
$this->line("Liste des sujets disponibles");
$this->line("----------------------------");
foreach ($sujets as $key => $sujet) {
$this->line("[" . $sujet->codeSujet . "] " . $sujet->libelle);
$this->newLine();
$this->line('Liste des sujets disponibles');
$this->line('----------------------------');
$this->line('[0] Tous les sujets');
foreach ($subjects as $subject) {
$this->line("[{$subject->codeSujet}] {$subject->libelle}");
}
$this->line("[0] Tous les sujets");
$sujetId = $this->ask('Pour quel sujet de média souhaitez vous executer le traitement ?');
$sujetId = $this->askWithCompletion(
'Pour quel sujet de média souhaitez vous executer le traitement ?',
$subjects->pluck('codeSujet')->toArray(),
0
);
if ($sujetId == "") {
if ($sujetId != 0 and !$subjects->pluck('codeSujet')->contains(\intval($sujetId))) {
$this->error('Id de sujet incorrect');
die();
return -1;
}
if ($sujetId == 0) {
$medias = Media::where('typemedia_id', 1)->with('Sujet.formats')->get();
} else {
$medias = Media::where('sujet_id', $sujetId)->where('typemedia_id', 1)->with('Sujet.formats')->get();
}
$sujetId = intval($sujetId);
if ($medias->count() == 0) {
$mediaCollection = Media::onlyTrashed()->with('sujet.formats');
if ($sujetId !== 0) {
$mediaCollection->where('sujet_id', $sujetId);
}
/** @var \Illuminate\Database\Eloquent\Collection<\App\Models\Media> */
$mediaCollection = $mediaCollection->get();
if (!$mediaCollection->count()) {
$this->error('Aucun média n\'a été trouvé');
die();
return -1;
}
$this->info($medias->count() . ' média(s) trouvé(s) - Début du traitement');
$bar = $this->output->createProgressBar(count($medias));
$this->info($mediaCollection->count() . ' média(s) trouvé(s) - Début du traitement');
$bar = $this->output->createProgressBar($mediaCollection->count());
$bar->start();
/** @var \App\Models\Media $media */
foreach ($medias as $media) {
// ---- Creation des vignettes de base
$this->createSysThumb($media);
// ---- Creation des vignettes en lien avec le sujet du média
$this->createThumb($media);
foreach ($mediaCollection as $media) {
try {
// ---- Creation des vignettes de base
$media->createThumbnail();
// ---- Creation des vignettes en lien avec le sujet du média
$media->createSubjectThumbnails();
} catch (\ImagickException | \RuntimeException $e) {
report($e);
}
$bar->advance();
}
$bar->finish();
$this->line("");
$this->newLine();
$this->info('Fin du traitement');
}
}

View file

@ -12,7 +12,7 @@ class ReindexElasticMedia extends Command
*
* @var string
*/
protected $signature = 'medias:reindex';
protected $signature = 'media:reindex';
/**
* The console command description.
@ -29,39 +29,48 @@ class ReindexElasticMedia extends Command
public function handle()
{
$this->info('Reindexation de la base médias dans Elasticsearch...');
$this->info('Test Présence...');
$this->info('ES: Test présence index...');
if (Media::indexExists()) {
$this->info('Suppression index...');
$this->info('ES: Suppression index...');
Media::deleteIndex();
}
$this->info('Création...');
$this->info('ES: Création index...');
Media::createIndex();
$pageNumber = 0;
$perPage = 200;
/** @var \Illuminate\Pagination\LengthAwarePaginator $medias */
$medias = Media::paginate($perPage);
$bar = $this->output->createProgressBar(count($medias));
/** @var \Illuminate\Pagination\LengthAwarePaginator $mediaCollection */
$mediaCollection = Media::paginate($perPage);
$bar->start($medias->total());
if (!$mediaCollection->total()) {
$this->info('Pas de medias');
}
$bar = $this->output->createProgressBar(count($mediaCollection));
$bar->start($mediaCollection->total());
// * LOOP
do {
if ($pageNumber > 0) {
/** @var \Illuminate\Pagination\LengthAwarePaginator $medias */
$medias = Media::paginate($perPage, ['*'], 'page', $pageNumber);
/** @var \Illuminate\Pagination\LengthAwarePaginator $mediaCollection */
$mediaCollection = Media::paginate($perPage, ['*'], 'page', $pageNumber);
}
foreach ($medias as $media) {
$media->addToIndex();
/** @var \App\Models\Media $media */
foreach ($mediaCollection->getCollection() as $media) {
/** @throws \RuntimeException */
$media->addToElasticSearch();
$bar->advance();
}
++$pageNumber;
} while ($medias->hasMorePages());
} while ($mediaCollection->hasMorePages());
$bar->finish();
$this->line('');
$this->newLine();
$this->info('Fin du traitement');
}
}

View file

@ -12,7 +12,7 @@ class ReindexElasticOneMedia extends Command
*
* @var string
*/
protected $signature = 'medias:reindexone {media_id}';
protected $signature = 'media:reindexone {media_id}';
/**
* The console command description.
@ -28,12 +28,14 @@ class ReindexElasticOneMedia extends Command
*/
public function handle()
{
$this->info('Reindexation du media ' . $this->argument('media_id') . ' dans Elasticsearch...');
$media = Media::withTrashed()->find($this->argument('media_id'));
$esExist = Media::searchByQuery(array('match' => array('arcadia_id' => "$media->arcadia_id")));
if ($esExist->totalHits() > 0) {
$media->removeFromIndex();
$mediaID = \strval($this->argument('media_id'));
$this->info("Reindexation du media $mediaID dans Elasticsearch...");
/** @var \App\Models\Media */
if (!($media = Media::withTrashed()->find($this->argument('media_id')))) {
$this->info("Pas de media $mediaID");
}
$media->addToIndex();
/** @throws \RuntimeException */
$media->addToElasticSearch();
$this->info("Media ID '$mediaID' Ajouté");
}
}

View file

@ -12,7 +12,7 @@ class SendMediasModificationsReport extends Command
*
* @var string
*/
protected $signature = 'medias:sendreport';
protected $signature = 'media:sendreport';
/**
* The console command description.

View file

@ -16,8 +16,10 @@ class Kernel extends ConsoleKernel
*/
protected function schedule(Schedule $schedule)
{
$schedule->job(XmlArcadiaMediasIn::class)->name('arcadia_medias_in')
$schedule->job(XmlArcadiaMediasIn::class)->name('Import Arcadia Media Files')
->onOneServer()->cron('*/2 * * * *');
$schedule->command('arcadia:import')->name('Import Arcadia XML Models')
->onOneServer()->cron('*/30 * * * *');
}
/**

23
app/Enums/ContactType.php Normal file
View file

@ -0,0 +1,23 @@
<?php
namespace App\Enums;
enum ContactType: int
{
case bug = 1;
case evolution = 2;
/**
* Get num label
*
* @return string
*/
public function label(): string
{
return match ($this) {
static::bug => trans('Signaler un bug'),
static::evolution => trans('Proposer une amélioration'),
default => trans('MISSING LABEL')
};
}
}

View file

@ -0,0 +1,11 @@
<?php
namespace App\Enums;
enum EdiMouvementType: string
{
case create = 'C';
case update = 'M';
case delete = 'S';
case reactivate = 'R';
}

View file

@ -1,10 +1,5 @@
<?php
/**
* En attente phpcs merge
* https://github.com/squizlabs/PHP_CodeSniffer/pull/3478
*/
namespace App\Enums;
enum LogType: int

View file

@ -0,0 +1,17 @@
<?php
namespace App\Enums;
enum MediaExtension: string
{
case ai = 'ai';
case gif = 'gif';
case jpeg = 'jpeg';
case jpg = 'jpg';
case mp4 = 'mp4';
case mp3 = 'mp3';
case pdf = 'pdf';
case png = 'png';
case psd = 'psd';
case svg = 'svg';
}

View file

@ -0,0 +1,103 @@
<?php
namespace App\Events;
use App\Models\Etiquette;
use App\Models\Media;
use App\Models\User;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class MediaChangedLabel extends MediaCreated
{
use Dispatchable;
use SerializesModels;
/**
* The user who created the media
*
* @var \App\Models\User
*/
private $user;
/**
* The media
*
* @var \App\Models\Media
*/
private $media;
/**
* The oldLabel
*
* @var \App\Models\Etiquette|null
*/
private $oldLabel;
/**
* The newLabel
*
* @var \App\Models\Etiquette|null
*/
private $newLabel;
/**
* Create a new event instance.
*
* @param \App\Models\User $user
* @param \App\Models\Media $media
* @param \App\Models\Etiquette|null $oldLabel
* @param \App\Models\Etiquette|null $newLabel
*/
public function __construct(
User $user,
Media $media,
Etiquette $oldLabel,
Etiquette $newLabel,
) {
$this->user = $user;
$this->media = $media;
$this->oldLabel = $oldLabel;
$this->newLabel = $newLabel;
}
/**
* Get User who triggered the event
*
* @return \App\Models\User
*/
public function getUser(): User
{
return $this->user;
}
/**
* Get the media
*
* @return \App\Models\Media
*/
public function getMedia(): Media
{
return $this->media;
}
/**
* Get the oldLabel
*
* @return \App\Models\Etiquette|null
*/
public function getOldLabel(): Etiquette|null
{
return $this->oldLabel;
}
/**
* Get the newLabel
*
* @return \App\Models\Etiquette|null
*/
public function getNewLabel(): Etiquette|null
{
return $this->newLabel;
}
}

View file

@ -0,0 +1,60 @@
<?php
namespace App\Events;
use App\Models\Media;
use App\Models\User;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class MediaCreated
{
use Dispatchable;
use SerializesModels;
/**
* The user who created the media
*
* @var \App\Models\User
*/
private $user;
/**
* The media
*
* @var \App\Models\Media
*/
private $media;
/**
* Create a new event instance.
*
* @param \App\Models\User $user
* @param \App\Models\Media $media
*/
public function __construct(User $user, Media $media)
{
$this->user = $user;
$this->media = $media;
}
/**
* Get User who triggered the event
*
* @return \App\Models\User
*/
public function getUser(): User
{
return $this->user;
}
/**
* Get the media
*
* @return \App\Models\Media
*/
public function getMedia(): Media
{
return $this->media;
}
}

View file

@ -0,0 +1,7 @@
<?php
namespace App\Events;
class MediaDestroyed extends MediaCreated
{
}

View file

@ -0,0 +1,60 @@
<?php
namespace App\Events;
use App\Models\Media;
use App\Models\User;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class MediaLinkWithArcadia
{
use Dispatchable;
use SerializesModels;
/**
* The user who created the media
*
* @var \App\Models\User
*/
private $user;
/**
* The media
*
* @var \App\Models\Media
*/
private $media;
/**
* Create a new event instance.
*
* @param \App\Models\User $user
* @param \App\Models\Media $media
*/
public function __construct(User $user, Media $media)
{
$this->user = $user;
$this->media = $media;
}
/**
* Get User who triggered the event
*
* @return \App\Models\User
*/
public function getUser(): User
{
return $this->user;
}
/**
* Get the media
*
* @return \App\Models\Media
*/
public function getMedia(): Media
{
return $this->media;
}
}

View file

@ -0,0 +1,7 @@
<?php
namespace App\Events;
class MediaMoved extends MediaCreated
{
}

View file

@ -0,0 +1,122 @@
<?php
namespace App\Events;
use App\Models\Sujet;
use App\Models\User;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class MediaSearched
{
use Dispatchable;
use SerializesModels;
/**
* The user who created the media
*
* @var \App\Models\User
*/
private $user;
/**
* The sujet
*
* @var \App\Models\Sujet
*/
private $sujet;
/**
* The searchString
*
* @var string
*/
private $searchString;
/**
* The filters
*
* @var object
*/
private $filters;
/**
* The dossier_id
*
* @var integer
*/
private $dossier_id;
/**
* Create a new event instance.
*
* @param \App\Models\User $user
* @param \App\Models\Sujet $sujet
* @param string $searchString
* @param object $filters
* @param integer $dossier_id
*/
public function __construct(
User $user,
Sujet $sujet,
string $searchString,
object $filters,
int $dossier_id
) {
$this->user = $user;
$this->sujet = $sujet;
$this->searchString = $searchString;
$this->filters = $filters;
$this->dossier_id = $dossier_id;
}
/**
* Get User who triggered the event
*
* @return \App\Models\User
*/
public function getUser(): User
{
return $this->user;
}
/**
* Get the sujet
*
* @return \App\Models\Sujet
*/
public function getSujet(): Sujet
{
return $this->sujet;
}
/**
* Get the searchString
*
* @return string
*/
public function getSearchString(): string
{
return $this->searchString;
}
/**
* Get the filters
*
* @return string
*/
public function getFilters(): object
{
return $this->filters;
}
/**
* Get the dossier_id
*
* @return integer
*/
public function getDossierId(): int
{
return $this->dossier_id;
}
}

View file

@ -0,0 +1,7 @@
<?php
namespace App\Events;
class MediaUpdated extends MediaCreated
{
}

View file

@ -2,6 +2,6 @@
namespace App\Exceptions;
class AbortXmlImportException extends \ErrorException
class AbortXmlImportException extends \RuntimeException
{
}

View file

@ -2,6 +2,6 @@
namespace App\Exceptions;
class ElasticSearchException extends \ErrorException
class ElasticSearchException extends \RuntimeException
{
}

View file

@ -3,25 +3,41 @@
namespace App\Http\Controllers;
use App\Models\ArcadiaLink;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Carbon;
class ArcadiaLinkController extends Controller
{
public function index(Request $request)
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
Auth::user()->authorizeRoles(config('roles.const.ADMIN'));
/** @var \App\Models\User */
$user = auth()->user();
$user->authorizeRoles(config('roles.const.ADMIN'));
$dt = Carbon::now('Europe/Paris')->subMinutes(15)->toDateTimeString();
$ano = ArcadiaLink::where('created_at', '<', $dt)->orderBy('id', 'DESC')->get();
return view('arcadialink.index', ['ano' => $ano]);
return view('arcadialinks.index', ['ano' => $ano]);
}
public function delete(Request $request)
/**
* Remove the specified resource from storage.
*
* @param \App\Models\ArcadiaLink $arcadia_link
* @return \Illuminate\Http\Response
*/
public function delete(ArcadiaLink $arcadia_link)
{
$id = $request->id;
$a = ArcadiaLink::find($id);
$a->delete();
return redirect()->route('arcadialink.index');
if ($arcadia_link->deleteOrFail()) {
return redirect()
->route('arcadialinks.index')
->with('warning', trans(
':model a bien été supprimé',
['model' => trans('ArcadiaLink')]
));
}
return back();
}
}

View file

@ -0,0 +1,22 @@
<?php
namespace App\Http\Controllers;
use App\Http\Requests\Bo\Ajax\GetArticleRequest;
use App\Models\Article;
use Illuminate\Http\JsonResponse;
class ArticleController
{
/**
* Renvoie un article par ID Arcadia
* @param \App\Http\Requests\Bo\Ajax\GetArticleRequest $request
* @return \Illuminate\Http\JsonResponse
*/
public function getArticle(GetArticleRequest $request): JsonResponse
{
return \response()->json([
'article' => Article::where('noArt', $request->arcadia_id)->firstOrFail()
]);
}
}

View file

@ -0,0 +1,82 @@
<?php
namespace App\Http\Controllers;
use App\Enums\ContactType;
use App\Http\Requests\Bo\Ajax\SendContactMessageRequest;
use App\Mail\ContactMail;
use App\Models\Dossier;
use App\Models\Format;
use App\Models\Recherche;
use App\Models\Sujet;
use Illuminate\Contracts\Database\Eloquent\Builder;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Mail;
class CommonController extends Controller
{
/**
* Show main interface
*
* @return \Illuminate\Contracts\Support\Renderable
*/
public function showInterface()
{
/** @var \App\Models\User */
$user = auth()->user();
/** @var \Illuminate\Database\Eloquent\Collection<\App\Models\Sujet> */
$sujets = $user->sujets;
/** @var \Illuminate\Database\Eloquent\Collection<\App\Models\Recherche> */
$recherches = Recherche::query()->whereHas('user', function (Builder $q) use ($user) {
$q->where('id', $user->id);
})->with('sujet')
->limit(10)
->orderBy('created_at', 'desc')
->get();
/** @var \Illuminate\Database\Eloquent\Collection<\App\Models\Dossier> */
$dossiers = Dossier::whereHas('users', function ($q) use ($user) {
$q->where('user_id', $user->id);
})->with('sujet')->get();
return view('home')->with([
'sujets' => $sujets, 'recherches' => $recherches,
'dossiers' => $dossiers
]);
}
/**
* Envoi d'un message
*
* @param \App\Http\Requests\Bo\Ajax\SendContactMessageRequest $request
* @return \Illuminate\Http\JsonResponse
*/
public function sendMessage(SendContactMessageRequest $request): JsonResponse
{
/** @var \App\Models\User $user */
$user = auth()->user();
Mail::to(env('MAIL_ADMIN_ADDRESS', "informatique.internet@ldc.fr"))
->send(new ContactMail(ContactType::from($request->type), $request->url, $request->message, $user));
return response()->json(['status' => 'OK']);
}
/**
* Get data by sujet
*
* @param \App\Models\Sujet $sujet
* @return \Illuminate\Http\JsonResponse
*/
public function getDatasBySujet(Sujet $sujet): JsonResponse
{
/** @var \Illuminate\Database\Eloquent\Collection<\App\Models\Format> */
$formats = Format::withoutGlobalScope('App\Scopes\SystemScope')
->where('system', 1)->get();
$formats = $formats->merge($sujet->formats);
return response()->json([
'typesvue' => $sujet->typeVues,
'typesvariantes' => $sujet->variantes,
'formats' => $formats
]);
}
}

View file

@ -1,70 +0,0 @@
<?php
namespace App\Http\Controllers;
use App\Models\Format;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Mail;
use App\Models\Sujet;
use App\Models\Recherche;
use App\Models\Dossier;
use App\Mail\Contact;
use Illuminate\Http\Request;
class CommunController extends Controller
{
/**
* page d'accueil
*
* @return \Illuminate\Contracts\Support\Renderable
*/
public function index()
{
$user = Auth::user();
$sujets = $user->sujets;
$paniers = Auth::user()->paniersFavoris;
$recherches = Recherche::where('user_id', $user->id)
->with("sujet")
->limit(10)
->orderBy("created_at", "desc")
->get();
$dossiers = Dossier::whereHas("users", function ($query) use ($user) {
$query->where('user_id', $user->id);
})
->with("sujet")
->get();
return view('home')->with(['sujets' => $sujets, 'recherches' => $recherches, 'dossiers' => $dossiers, 'paniers' => $paniers]);
}
/**
* Envoi d'un message
*
*/
public function sendMessage(Request $request)
{
$type = $request->input('type');
$url = $request->input('url');
$message = $request->input('message');
if (Auth::check()) {
$user = auth()->user();
Mail::to(env('MAIL_ADMIN_ADDRESS', "informatique.internet@ldc.fr"))
->send(new Contact($type, $url, $message, $user));
}
return json_encode(array('status' => "OK"));
}
public function getDatasBySujet(Request $request)
{
$sujet_id = $request->sujet_id;
$sujet = Sujet::findOrFail($sujet_id);
$response['typesvue'] = $sujet->typeVues;
$response['typesvariantes'] = $sujet->variantes;
$response['formats'] = array_merge(Format::withoutGlobalScope('App\Scopes\SystemScope')->where('system', 1)->get()->toArray(), $sujet->formats->toArray());
return response()->json($response);
}
}

View file

@ -2,17 +2,122 @@
namespace App\Http\Controllers;
use App\Http\Requests\Bo\Ajax\FetchFoldersRequest;
use App\Http\Requests\Bo\Ajax\LoadFoldersRequest;
use App\Http\Requests\Bo\Folders\StoreDepotFolderRequest;
use App\Http\Requests\Bo\Folders\StoreFolderRequest;
use App\Http\Requests\Bo\Folders\UpdateFolderRequest;
use App\Http\Resources\NestedDossiersListResource;
use App\Models\Dossier;
use App\Models\Sujet;
use App\Models\Marque;
use App\Models\Media;
use App\Models\Variante;
use App\Models\Format;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
class DossierController extends Controller
{
/**
* Ajax Load folders
*
* @param \App\Http\Requests\Bo\Ajax\LoadFoldersRequest $request
* @return \Illuminate\Http\JsonResponse
*/
public function loadFolders(LoadFoldersRequest $request): JsonResponse
{
/** @var \App\Models\User */
$user = Auth::user();
$folders = [];
$select = ['id', 'libelle', 'system'];
/** @var \Illuminate\Database\Eloquent\Collection<\App\Models\Dossier> Dossiers publiques */
$publicFolders = Dossier::whereHas('sujet', function ($q) use ($request) {
$q->where('codeSujet', $request->sujet_id);
})->whereIsPrivate(false)->whereNull('parent_id')->select($select)->get();
// On récupère les dossiers privés.
/** @var \Illuminate\Database\Eloquent\Builder */
$privateQuery = Dossier::whereHas('sujet', function ($q) use ($request) {
$q->where('codeSujet', $request->sujet_id);
})->select($select)->whereIsPrivate(true);
// If not admin, get using brands.
if (!$user->hasRole(config('roles.const.ADMIN'))) {
/** @var \Illuminate\Database\Eloquent\Collection<integer> Codes marques */
$marques = $user->marques()->pluck('codMarq');
$privateQuery->whereHas('marques', function ($q) use ($marques) {
$q->whereIn('codMarq', $marques);
});
}
/** @var \Illuminate\Database\Eloquent\Collection<\App\Models\Dossier> Dossiers privés */
$privateFolders = $privateQuery->get();
$foldersCollection = $publicFolders->merge($privateFolders);
$foldersCollection = $foldersCollection->sortBy('libelle', SORT_NATURAL | SORT_FLAG_CASE)
->sortBy('favoris')->values();
// Ajout du dépôt de fichier pour les admin.
if ($user->hasRole(config('roles.const.ADMIN'))) {
/** @var \Illuminate\Database\Eloquent\Collection<\App\Models\Dossier> Dossiers depots */
$depotQuery = Dossier::whereNull('parent_id')
->where('system', true)
->orderBy('libelle', 'ASC')
->get();
$foldersCollection = $foldersCollection->merge($depotQuery);
}
$folders['data'] = new NestedDossiersListResource($foldersCollection);
$folders['racineCount'] = Media::whereSujetId($request->sujet_id)
->whereNull('dossier_id')
->where(function ($query) use ($user) {
$query->where('statut', config('services.statut.public_etendu'))
->orWhere('statut', config('services.statut.public'))
->orWhere('created_by', $user->id);
})->count();
return response()->json($folders);
}
/**
* Chargement des dossiers
*
* @param \App\Http\Requests\Bo\Ajax\FetchFoldersRequest $request
* @return \Illuminate\Http\JsonResponse
*/
public function loadFolder(FetchFoldersRequest $request): JsonResponse
{
/** @var \App\Models\User */
$user = auth()->user();
$response = [];
$response['variantes'] = Variante::where('sujet_id', $request->sujetId)->get();
/** @var \Illuminate\Database\Eloquent\Collection<\App\Models\Format> */
$FormatsSujet = Format::whereHas('sujets', function ($query) use ($request) {
$query->where('sujet_id', $request->sujetId);
})->get();
/** @var \Illuminate\Database\Eloquent\Collection<\App\Models\Format> */
$FormatsSystem = Format::withoutGlobalScope('App\Scopes\SystemScope')
->where('system', true)->get();
$response['formats'] = $FormatsSujet->merge($FormatsSystem);
$response['draggable'] = $user->hasRole([config('roles.const.ADMIN'), config('roles.const.REDACTEUR')]);
// Envoi du role .
$response['role'] = $user->role;
return \response()->json($response);
}
// * CRUD
/**
* Display a listing of the resource.
*
@ -20,9 +125,17 @@ class DossierController extends Controller
*/
public function index()
{
Auth::user()->authorizeRoles(config('roles.const.ADMIN'));
$dossiers = Dossier::whereNull('parent_id')->where('system', false)->orderBy('libelle', 'asc')->get();
$sujets = Sujet::where('sujet_dam', 1)->get();
/** @var \App\Models\User */
$user = auth()->user();
$user->authorizeRoles(config('roles.const.ADMIN'));
/** @var \Illuminate\Database\Eloquent\Collection<\App\Models\Dossier> */
$dossiers = Dossier::whereNull('parent_id')
->where('system', false)
->orderBy('libelle', 'asc')
->get();
/** @var \Illuminate\Database\Eloquent\Collection<\App\Models\Sujet> */
$sujets = Sujet::where('sujet_dam', true)->get();
return view('dossiers.index')->with([
'dossiers' => $dossiers,
@ -33,458 +146,159 @@ class DossierController extends Controller
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Contracts\View\View|\Illuminate\Contracts\View\Factory
*/
public function create()
public function create(Request $request)
{
Auth::user()->authorizeRoles(config('roles.const.ADMIN'));
$marques = Marque::all();
$sujets = Sujet::where('sujet_dam', 1)->get();
return view('dossiers.create')->with(['marques' => $marques, 'sujets' => $sujets]);
}
if ($request->sub) {
/** @var \Illuminate\Database\Eloquent\Collection<\App\Models\Dossier> */
$dossiers = Dossier::whereNull('parent_id')->where('system', false)
->orderBy('libelle', 'asc')->get();
return view('dossiers.create-sub')->with(['dossiers' => $dossiers]);
}
public function createSub()
{
$dossiers = Dossier::whereNull('parent_id')->where('system', false)->orderBy('libelle', 'asc')->get();
return view('dossiers.create-sub')->with(['dossiers' => $dossiers]);
/** @var \App\Models\User */
$user = auth()->user();
$user->authorizeRoles(config('roles.const.ADMIN'));
$marques = Marque::all();
/** @var \Illuminate\Database\Eloquent\Collection<\App\Models\Sujet> */
$sujets = Sujet::where('sujet_dam', true)->get();
return view('dossiers.create')->with([
'marques' => $marques, 'sujets' => $sujets
]);
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Http\Requests\Bo\Folders\StoreFolderRequest $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
public function store(StoreFolderRequest $request)
{
Auth::user()->authorizeRoles(config('roles.const.ADMIN'));
$validatedData = $request->validate([
'libelle' => 'required',
'sujet' => 'required',
'status' => 'required'
]);
DB::transaction(function () use ($request) {
/** @var \App\Models\User */
$user = auth()->user();
$user->authorizeRoles(config('roles.const.ADMIN'));
$dossierExist = Dossier::where('libelle', $request->libelle)->where('sujet_id', $request->sujet)->first();
if ($dossierExist) {
session()->flash('error', "Ce nom de dossier est déjà présent dans l'application pour ce sujet. Ajout impossible.");
return redirect()->route('dossier.create');
} else {
// ---- Le dossier
$dossier = new Dossier();
$dossier->libelle = $request->libelle;
$dossier->description = $request->description;
$dossier->is_private = $request->status;
$dossier->sujet()->associate($request->sujet);
$dossier = new Dossier();
$dossier->fill($request->validated());
if ($dossier->save()) {
if ($request->sub) {
/** @var \App\Models\Dossier */
$parent_dossier = Dossier::findOrFail($request->parent_id);
$dossier->sujet()->associate($parent_dossier->sujet);
} else {
$dossier->sujet()->associate($request->sujet);
}
if ($dossier->saveOrFail()) {
// ---- Les marques
$sMarques = $request->marques;
if ($sMarques != "") {
$marques = explode(",", $sMarques);
foreach ($marques as $marqueId) {
$dossier->marques()->attach($marqueId);
}
if ($request->marques) {
$dossier->marques()->sync($request->marques);
}
session()->flash('message', "Le dossier a été enregistré");
return redirect()->route('dossier.edit', ['dossier' => $dossier]);
} else {
session()->flash('error', "Une erreur s'est produite, ajout impossible");
return redirect()->route('dossier.create');
return redirect()->route('dossier.edit', ['dossier' => $dossier])
->with('success', 'Le dossier a été enregistré');
}
}//end if
}
public function storeSub(Request $request)
{
Auth::user()->authorizeRoles(config('roles.const.ADMIN'));
$validatedData = $request->validate([
'libelle' => 'required',
'parent_id' => 'required',
]);
$dossierExist = Dossier::where('libelle', $request->libelle)->first();
$parent_dossier = Dossier::findOrFail($request->parent_id);
if ($dossierExist) {
session()->flash('error', "Ce nom de dossier est déjà présent dans l'application pour ce sujet. Ajout impossible.");
return redirect()->route('dossier.create');
} else {
// ---- Le dossier
$dossier = new Dossier();
$dossier->libelle = $request->libelle;
$dossier->description = $request->description;
$dossier->is_private = 0;
$dossier->parent_id = $request->parent_id;
$dossier->sujet_id = $parent_dossier->sujet_id;
if ($dossier->save()) {
session()->flash('message', "Le dossier a été enregistré");
return redirect()->route('dossier.edit', ['dossier' => $dossier]);
} else {
session()->flash('error', "Une erreur s'est produite, ajout impossible");
return redirect()->route('dossier.create');
}
}
}
/**
* Display the specified resource.
*
* @param \App\Models\Dossier $dossier
* @return \Illuminate\Http\Response
*/
public function show(Dossier $dossier)
{
});
return back();
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\Dossier $dossier
* @return \Illuminate\Http\Response
* @return \Illuminate\Contracts\View\View|\Illuminate\Contracts\View\Factory
*/
public function edit(Dossier $dossier)
{
Auth::user()->authorizeRoles(config('roles.const.ADMIN'));
/** @var \App\Models\User */
$user = auth()->user();
$user->authorizeRoles(config('roles.const.ADMIN'));
$marques = Marque::all();
/** @var \Illuminate\Database\Eloquent\Collection<\App\Models\Marque> */
$dossierMarques = $dossier->marques;
$marques = Marque::all();
$dossierSujets = $dossier->sujets;
$sujets = Sujet::where('sujet_dam', 1)->get();
return view('dossiers.edit')->with(['dossier' => $dossier, 'dossierMarques' => $dossierMarques, 'marques' => $marques, 'sujets' => $sujets]);
/** @var \Illuminate\Database\Eloquent\Collection<\App\Models\Sujet> */
$dossierSujets = $dossier->sujets;
/** @var \Illuminate\Database\Eloquent\Collection<\App\Models\Sujet> */
$sujets = Sujet::where('sujet_dam', true)->get();
return view('dossiers.edit')->with([
'dossier' => $dossier,
'dossierMarques' => $dossierMarques,
'marques' => $marques,
'sujets' => $sujets
]);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\Dossier $dossier
* @return \Illuminate\Http\Response
* @param \App\Http\Requests\Bo\Folders\UpdateFolderRequest $request
* @param \App\Models\Dossier $dossier
* @return \Illuminate\Http\RedirectResponse
*/
public function update(Request $request, Dossier $dossier)
public function update(UpdateFolderRequest $request, Dossier $dossier): RedirectResponse
{
Auth::user()->authorizeRoles(config('roles.const.ADMIN'));
DB::transaction(function () use ($request, $dossier) {
/** @var \App\Models\User */
$user = auth()->user();
$user->authorizeRoles(config('roles.const.ADMIN'));
if ($dossier->parent_id === null) {
$validatedData = $request->validate([
'libelle' => 'required',
'sujet' => 'required',
'status' => 'required'
]);
// ---- Le dossier
$dossier->fill($request->validated());
$dossierExist = Dossier::where('libelle', $request->libelle)->where('sujet_id', $request->sujet)->where('id', '<>', $dossier->id)->first();
if ($dossierExist) {
session()->flash('error', "Ce nom de dossier est déjà présent dans l'application pour ce sujet. Ajout impossible.");
return redirect()->route('dossier.edit', ['dossier' => $dossier]);
} else {
// ---- Le dossier
$dossier->libelle = $request->libelle;
$dossier->description = $request->description;
$dossier->is_private = $request->status;
$dossier->sujet()->dissociate();
$dossier->sujet()->associate($request->sujet);
if ($dossier->save()) {
// ---- Les marques
$dossier->marques()->detach();
$sMarques = $request->marques;
if ($sMarques != "") {
$marques = explode(",", $sMarques);
foreach ($marques as $marqueId) {
$dossier->marques()->attach($marqueId);
}
}
session()->flash('message', "Le dossier a été mis à jour");
return redirect()->route('dossier.edit', ['dossier' => $dossier]);
} else {
session()->flash('error', "Une erreur s'est produite, enregistrement impossible");
return redirect()->route('dossier.edit');
}
}//end if
} else {
$validatedData = $request->validate([
'libelle' => 'required',
]);
$dossierExist = Dossier::where('libelle', $request->libelle)->where('sujet_id', $request->sujet)->where('id', '<>', $dossier->id)->first();
if ($dossierExist) {
session()->flash('error', "Ce nom de dossier est déjà présent dans l'application pour ce sujet. Ajout impossible.");
return redirect()->route('dossier.edit', ['dossier' => $dossier]);
} else {
// ---- Le dossier
$dossier->libelle = $request->libelle;
$dossier->description = $request->description;
if ($dossier->save()) {
session()->flash('message', "Le dossier a été mis à jour");
return redirect()->route('dossier.edit', ['dossier' => $dossier]);
} else {
session()->flash('error', "Une erreur s'est produite, enregistrement impossible");
return redirect()->route('dossier.edit');
if ($dossier->saveOrFail()) {
// ---- Les marques
if ($request->marques) {
$dossier->marques()->sync($request->marques);
}
return redirect()->route('dossier.edit', ['dossier' => $dossier])
->with('success', 'Le dossier a été mis à jour');
}
}//end if
});
return back();
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\Dossier $dossier
* @return \Illuminate\Http\Response
* @return \Illuminate\Http\RedirectResponse
*/
public function destroy(Dossier $dossier)
public function destroy(Dossier $dossier): RedirectResponse
{
Auth::user()->authorizeRoles(config('roles.const.ADMIN'));
if ($dossier->delete()) {
return redirect(route('dossier.index'));
} else {
session()->flash('error', 'Erreur lors de la suppression');
return redirect()->route('dossier.edit', ['user' => $dossier]);
/** @var \App\Models\User */
$user = auth()->user();
$user->authorizeRoles(config('roles.const.ADMIN'));
if ($dossier->deleteOrFail()) {
return \response()->redirectToRoute('dossier.index')
->with('warning', trans('Le dossier à été supprimé'));
}
}
/**
* Chargement des dossiers
*
*/
public function loadFolder(Request $request)
{
$response = array();
$sujetId = $request->input('sujetId');
$response['variantes'] = Variante::where('sujet_id', $sujetId)->get();
$FormatsSujet = Format::whereHas('sujets', function ($query) use ($sujetId) {
$query->where('sujet_id', $sujetId);
})->get();
$FormatsSystem = Format::withoutGlobalScope('App\Scopes\SystemScope')->where('system', true)->get();
$response['formats'] = $FormatsSujet->merge($FormatsSystem);
if (Auth::user()->hasRole([config('roles.const.ADMIN'), config('roles.const.REDACTEUR')])) {
$response['draggable'] = true;
} else {
$response['draggable'] = false;
}
// Envoi du role
$response['role'] = Auth::user()->role;
return json_encode($response);
}
/**
* Ajouter un dossier
*
*/
public function addFolder(Request $request)
{
$response = array();
Auth::user()->authorizeRoles([config('roles.const.ADMIN'), config('roles.const.REDACTEUR')]);
$parent_id = $request->input('parent_id');
$libelle = $request->input('libelle');
$description = $request->input('description');
// ---- Le dossier
$dossier = new Dossier();
$dossier->libelle = htmlspecialchars($libelle);
$dossier->description = $description;
$dossier->parent_id = $parent_id;
$dossierParent = Dossier::where('id', $parent_id)->first();
if ($parent_id == 1 || $dossierParent->system) {
// dossier de dépôt
$dossier->system = true;
} else {
$dossier->system = false;
}
$dossier->sujet_id = $dossierParent->sujet_id;
$dossier->save();
$response['folder_id'] = $dossier->id;
$response['system'] = $dossier->system ? 1 : 0;
return json_encode($response);
return back();
}
/**
* Ajouter un dossier de dépôt
*
* @param \App\Http\Requests\Bo\Folders\StoreDepotFolderRequest $request
* @return \Illuminate\Http\JsonResponse
*/
public function addDepotFolder(Request $request)
public function addDepotFolder(StoreDepotFolderRequest $request): JsonResponse
{
$response = array();
$parent_id = $request->input('parent_id');
$libelle = $request->input('libelle');
$description = $request->input('description');
// ---- Le dossier
$dossier = new Dossier();
$dossier->libelle = htmlspecialchars($libelle);
$dossier->description = $description;
$dossier->parent_id = 1;
$dossier->system = true;
$dossier->save();
$response['folder_id'] = $dossier->id;
return json_encode($response);
}
/**
* supprimer un dossier
*
*/
public function removeFolder(Request $request)
{
Auth::user()->authorizeRoles([config('roles.const.ADMIN'), config('roles.const.REDACTEUR')]);
$dossier_id = $request->input('dossier_id');
// ---- Le dossier
$dossier = Dossier::where('id', $dossier_id)->first();
if ($dossier && !is_null($dossier->parent_id)) {
if ($dossier->delete()) {
return json_encode($dossier->parent_id);
}
}
return json_encode(false);
}
/**
* déplacer un dossier
*
*/
public function moveFolder(Request $request)
{
Auth::user()->authorizeRoles([config('roles.const.ADMIN'), config('roles.const.REDACTEUR')]);
$dossier_id = $request->input('dossier_id');
$parent_id = $request->input('parent_id');
$sujet_id = $request->input('sujet_id');
// ---- Le dossier
$dossier = Dossier::where('id', $dossier_id)->first();
if ($dossier && !is_null($dossier->parent_id)) {
$dossier->parent_id = $parent_id;
if ($dossier->save()) {
Media::where('dossier_id', $dossier_id)->update(['sujet_id' => $sujet_id]);
return json_encode(true);
}
}
return json_encode(false);
}
/**
* renommer un dossier
*
*/
public function renameFolder(Request $request)
{
Auth::user()->authorizeRoles([config('roles.const.ADMIN'), config('roles.const.REDACTEUR')]);
$dossier_id = $request->input('dossier_id');
$libelle = $request->input('libelle');
// ---- Le dossier
$dossier = Dossier::where('id', $dossier_id)->first();
if ($dossier && !is_null($dossier->parent_id)) {
$dossier->libelle = $libelle;
if ($dossier->save()) {
return json_encode(true);
}
}
return json_encode(false);
}
/**
* get propriétés d'un dossier
*
*/
public function getFolderProperty(Request $request)
{
$response = array();
$dossier_id = $request->input('dossier_id');
// ---- Le dossier
$dossier = Dossier::where('id', $dossier_id)->first();
if ($dossier) {
$response["data"] = $dossier;
}
return json_encode($response);
}
/**
* enregistre les propriétés d'un dossier
*
*/
public function saveFolderProperty(Request $request)
{
$dossier_id = $request->input('dossier_id');
$libelle = $request->input('libelle');
$description = $request->input('description');
// ---- Le dossier
$dossier = Dossier::where('id', $dossier_id)->first();
if ($dossier && !is_null($dossier->parent_id) && strlen($libelle) > 3) {
$dossier->libelle = $libelle;
$dossier->description = $description;
$dossier->save();
}
return json_encode(true);
}
public function loadFolders(Request $request)
{
$folders = array();
$user = Auth::user();
$sujet_id = $request->sujet_id;
$dossierQuery = Dossier::where([
['sujet_id', $sujet_id],
['is_private', 0]
])
->whereNull('parent_id');
$dossierQuery = $dossierQuery->get();
// On récupère les dossiers privés
if ($user->hasRole(config('roles.const.ADMIN'))) {
$privateQuery = Dossier::where([
['is_private', '=', 1],
['sujet_id', '=', $sujet_id],
])->get();
} else {
$marques = $user->marques()->pluck("marque_id");
$privateQuery = Dossier::where([
['is_private', '=', 1],
['sujet_id', '=', $sujet_id],
])->whereHas("marques", function ($query) use ($marques) {
$query->whereIn("marque_id", $marques);
})->get();
}
$dossierQuery = $dossierQuery->merge($privateQuery);
$dossierQuery = $dossierQuery->sortBy('libelle', SORT_NATURAL | SORT_FLAG_CASE)->values();
// Ajout du dépôt de fichier pour les admin
if ($user->hasRole(config('roles.const.ADMIN'))) {
$depotQuery = Dossier::whereNull('parent_id')
->where('system', true)
->orderBy('libelle', 'ASC')
->get();
$folders['data'] = $dossierQuery->merge($depotQuery);
} else {
$folders['data'] = $dossierQuery;
}
$folders['racineCount'] = Media::where('sujet_id', $sujet_id)
->whereNull('dossier_id')
->where(function ($query) use ($user) {
$query->where('statut', config('services.statut.public_etendu'))
->orWhere('statut', config('services.statut.public'))
->orWhere('created_by', $user->id);
})
->count();
return response()->json($folders);
$dossier = new Dossier($request->validated());
$dossier->parent_id = 1;
$dossier->system = true;
$dossier->saveOrFail();
return \response()->json([
'folder_id' => $dossier->id
]);
}
}

File diff suppressed because it is too large Load diff

View file

@ -2,11 +2,11 @@
namespace App\Http\Controllers;
use App\Http\Requests\Bo\AjaxAddMediasBasketRequest;
use App\Http\Requests\Bo\AjaxCreateBasketRequest;
use App\Http\Requests\Bo\AjaxDestroyBasketRequest;
use App\Http\Requests\Bo\AjaxRemoveMediasBasketRequest;
use App\Http\Requests\Bo\AjaxSaveBasketPropsRequest;
use App\Http\Requests\Bo\Ajax\AddMediasBasketRequest;
use App\Http\Requests\Bo\Ajax\CreateBasketRequest;
use App\Http\Requests\Bo\Ajax\DestroyBasketRequest;
use App\Http\Requests\Bo\Ajax\RemoveMediasBasketRequest;
use App\Http\Requests\Bo\Ajax\SaveBasketPropsRequest;
use Illuminate\Support\Str;
use App\Models\Panier;
use App\Models\Format;
@ -53,19 +53,19 @@ class PanierController extends Controller
/**
* Ajout de média à un panier
*
* @param AjaxAddMediasBasketRequest $request
* @param \App\Http\Requests\Bo\Ajax\AddMediasBasketRequest $request
* @return \Illuminate\Http\JsonResponse
*/
public function addMediasBasket(AjaxAddMediasBasketRequest $request)
public function addMediasBasket(AddMediasBasketRequest $request)
{
/** @var \App\Models\Panier $panier */
$panier = Panier::whereId($request->panier_id)
->with('medias')->firstOrFail();
->with('mediaList')->firstOrFail();
// * Sync every media to basket
$panier->medias()->sync(array_merge(
$panier->medias()->pluck('id')->all(),
$request->medias
$panier->mediaList()->sync(array_merge(
$panier->mediaList()->pluck('id')->all(),
$request->mediaList
));
return response()->json();
@ -74,20 +74,20 @@ class PanierController extends Controller
/**
* Suppression de média à un panier
*
* @param AjaxRemoveMediasBasketRequest $request
* @param \App\Http\Requests\Bo\Ajax\RemoveMediasBasketRequest $request
* @return \Illuminate\Http\JsonResponse
*/
public function removeMediasBasket(AjaxRemoveMediasBasketRequest $request)
public function removeMediasBasket(RemoveMediasBasketRequest $request)
{
/** @var \App\Models\Panier $panier */
$panier = Panier::whereId($request->panier_id)
->with('medias')->firstOrFail();
->with('mediaList')->firstOrFail();
/** @var \App\Models\Media $media */
$media = Media::whereId($request->media_id)->firstOrFail();
$panier->medias()->detach($media);
$panier->mediaList()->detach($media);
return response()->json(true);
}
@ -95,10 +95,10 @@ class PanierController extends Controller
/**
* Ajoute un panier
*
* @param AjaxCreateBasketRequest $request
* @param \App\Http\Requests\Bo\Ajax\CreateBasketRequest $request
* @return \Illuminate\Http\JsonResponse
*/
public function createBasket(AjaxCreateBasketRequest $request)
public function createBasket(CreateBasketRequest $request)
{
/** @var \App\Models\User $user */
$user = auth()->user();
@ -115,10 +115,10 @@ class PanierController extends Controller
/**
* Supprimer un panier
*
* @param AjaxDestroyBasketRequest $request
* @param \App\Http\Requests\Bo\Ajax\DestroyBasketRequest $request
* @return \Illuminate\Http\JsonResponse
*/
public function destroyBasket(AjaxDestroyBasketRequest $request)
public function destroyBasket(DestroyBasketRequest $request)
{
/** @var \App\Models\Panier $basket */
$basket = Panier::whereId($request->basket_id)->firstOrFail();
@ -133,7 +133,7 @@ class PanierController extends Controller
/**
* Page publique d'un panier
*
* @param Panier $panier
* @param \App\Models\Panier $panier
* @return \Illuminate\View\View|\Illuminate\Contracts\View\Factory
*/
public function showBasket(Panier $panier)
@ -149,7 +149,7 @@ class PanierController extends Controller
}
}
/** @var \Illuminate\Database\Eloquent\Collection $formats */
/** @var \Illuminate\Database\Eloquent\Collection<\App\Models\Format> $formats */
$formats = Format::withoutGlobalScope('App\Scopes\SystemScope')
->where('system', true)->get();
return view('panier.show')->with([
@ -161,10 +161,10 @@ class PanierController extends Controller
/**
* Enregistre les propriétés d'un panier
*
* @param AjaxSaveBasketPropsRequest $request
* @param \App\Http\Requests\Bo\Ajax\SaveBasketPropsRequest $request
* @return \Illuminate\Http\JsonResponse
*/
public function saveBasketProperty(AjaxSaveBasketPropsRequest $request)
public function saveBasketProperty(SaveBasketPropsRequest $request)
{
/** @var \App\Models\Panier $panier */
$panier = Panier::whereId($request->basket_id)->firstOrFail();

View file

@ -4,25 +4,33 @@ namespace App\Http\Controllers;
use App\Models\Media;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class RecoveryController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
Auth::user()->authorizeRoles(config('roles.const.ADMIN'));
/** @var \App\Models\User */
$user = auth()->user();
$user->authorizeRoles(config('roles.const.ADMIN'));
return view('recovery.index');
}
/**
* Check if ArcadiaId exists.
*
* @param Request $request
* @return \Illuminate\Http\JsonResponse
*/
public function checkArcadiaId(Request $request)
{
$response = false;
$arcadia_id = $request->id;
$media = Media::onlyTrashed()->where('arcadia_id', '=', $arcadia_id)->first();
if ($media) {
$response = true;
}
return json_encode($response);
return \response()->json(
Media::onlyTrashed()->where('arcadia_id', '=', \intval($request->id))->exists()
);
}
}

View file

@ -2,548 +2,317 @@
namespace App\Http\Controllers;
use App\Http\Traits\MediaTools;
use App\Models\Historique;
use App\Enums\MediaExtension;
use App\Http\Requests\Bo\Ajax\UploadMediaFileRequest;
use App\Lib\ToolboxHelper;
use App\Models\Copyright;
use App\Models\Dossier;
use App\Models\Etiquette;
use App\Models\Langue;
use App\Models\Media;
use App\Models\Site;
use App\Models\Sujet;
use App\Models\TypeMedia;
use App\Models\User;
use App\Traits\Http\HandlesMedia;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Pion\Laravel\ChunkUpload\Exceptions\UploadMissingFileException;
use Pion\Laravel\ChunkUpload\Receiver\FileReceiver;
class UploadController extends Controller
{
use MediaTools;
use HandlesMedia;
public function index(Request $request)
/**
* Show upload form
*
* @param Request $request
* @return \Illuminate\Contracts\Validation\Validator|\Illuminate\Contracts\Validation\Factory
*/
public function showUploadForm(Request $request)
{
// ---- Vérification du token de sécurité
// TODO: Quand le DAM sera ouvert au public, Enforce security with dynamic tokens.
// ---- Vérification du token de sécurité .
$token = $request->get('token');
if ($token != env('TOKEN_DEPOT', "c8c4613a-236c-4b06-95f6-a9c9c6c18861")) {
return abort(404);
}
$sites = Site::orderBy('libelle')->get();
return view('upload.show')->with(
[
return view('upload.show')->with([
'sites' => $sites,
]
);
}
public function storeMedia(Request $request)
{
$uid = $request->input('uid');
$sujet_id = $request->input('sujet_id');
$dossier_id = $request->input('dossier_id');
$replaceMediaId = $request->input('replaceMediaId');
if ($dossier_id == 0) {
$dossier_id = null;
}
$headers = $request->headers->all();
$acceptFileTypes = array('gif','jpeg', 'jpg','png','mp4','mp3','psd','ai','svg','pdf');
if ($request->hasFile('files')) {
$filesa = [];
/** @var array<\Illuminate\Http\UploadedFile> */
$files = $request->file('files');
foreach ($files as $file) {
$is_last_chunk = false;
$is_chunked_upload = !empty($headers['content-range']);
if ($is_chunked_upload) {
if (preg_match('|(\d+)/(\d+)|', $headers['content-range'][0], $range)) {
if ($range[1] == $range[2] - 1) {
$is_last_chunk = true;
}
}
}
$extension = strtolower($file->getClientOriginalExtension());
$originalName = str_replace("." . $extension, "", $file->getClientOriginalName());
if (!in_array($extension, $acceptFileTypes)) {
return array("false");
}
if ($is_chunked_upload) {
$filename = $uid . "_" . $range[1] . "." . $extension;
} else {
$filename = $uid . '.' . $extension;
}
$uploadPath = public_path() . '/uploads/';
$file->move($uploadPath, $filename);
// * si c'est le dernier morceux d'un fichier
if ($is_last_chunk) {
if ($dossier = opendir($uploadPath)) {
$dirFiles = array();
// * on compile tous les chunk du fichier
while (false !== ($fichier = readdir($dossier))) {
if ($fichier != '.' && $fichier != '..') {
if (strpos($fichier, $uid) !== false) {
$dirFiles[$fichier] = str_replace(
".{$extension}",
"",
str_replace("{$uid}_", "", $fichier)
);
}
}
}
closedir($dossier);
// * on les trie pour les assembler dans le bon ordre
asort($dirFiles, SORT_NUMERIC);
// * on les assemble dans un fichier final
$filename = $uid . '.' . $extension;
foreach ($dirFiles as $key => $fichier) {
$file = fopen($uploadPath . $key, 'rb');
$buff = fread($file, filesize($uploadPath . $key));
fclose($file);
$final = fopen($uploadPath . $filename, 'a');
$write = fwrite($final, $buff);
fclose($final);
unlink($uploadPath . $key);
}
}//end if
}//end if
// * si c'est le dernier morceau d'un fichier ou que c'est un envoi simple
if ($is_last_chunk || !$is_chunked_upload) {
$destinationPath = $this->getMediaFolder() . "/";
// * si on upload un média pour remplacer un fichier par un autre
if ($replaceMediaId != 0) {
// * on récupère le média à modifier
/** @var \App\Models\Media|null */
$media = Media::where('id', $replaceMediaId)->first();
// * On déplace le fichier dans le répertoire des médias
if (!Storage::move("uploads/{$filename}", $destinationPath . $filename)) {
throw new \ErrorException(
"Could not move uploaded file $filename into {$destinationPath}{$filename}"
);
}
// * supprime les fichiers médias stockés sur disque
$filesfF = Storage::files($media->folder . "/");
$filepath = preg_quote($media->folder . $media->uid, '/');
$matchingFiles = preg_grep('/^' . $filepath . '/', $filesfF);
Storage::delete($matchingFiles);
$media->isDefault = 0;
$media->save();
} else {
// * On déplace le fichier dans le répertoire des médias
if (!Storage::move("uploads/{$filename}", $destinationPath . $filename)) {
throw new \ErrorException(
"Could not move uploaded file $filename into {$destinationPath}{$filename}"
);
}
// * on créé un média en bdd
$media = new Media();
$media->dossier_id = $dossier_id;
$media->sujet_id = $sujet_id;
// * Par défaut FR
$media->langue_id = 1;
// * Par défaut propriété de la marque
$media->copyright_id = 3;
}//end if
$media->extension = $extension;
$media->folder = $destinationPath;
if ($replaceMediaId == 0) {
$media->libelle = mb_substr($originalName, 0, 50, "UTF-8");
$media->created_by = Auth::user()->id;
}
$media->uid = $uid;
$media->taille = $this->formatBytes(Storage::size($destinationPath . $filename));
switch ($extension) {
// * Photo (1)
case 'gif':
case 'jpeg':
case 'jpg':
case 'png':
case 'ai':
case 'pdf':
case 'psd':
$media->typemedia_id = 1;
$im = new \Imagick($destinationPath . $filename);
if (in_array($extension, array("pdf", "ai", "psd", "gif"))) {
$im->setIteratorIndex(0);
}
$resolutions = $im->getImageResolution();
$media->resolution = round($resolutions['x'] * 2.54);
$imageprops = $im->getImageGeometry();
$media->largeur = $imageprops['width'];
$media->hauteur = $imageprops['height'];
if ($media->resolution != 0) {
$media->largeur_mm = ceil(($media->largeur * 2.54 / $media->resolution) * 10);
$media->hauteur_mm = ceil(($media->hauteur * 2.54 / $media->resolution) * 10);
} else {
$media->largeur_mm = "";
$media->hauteur_mm = "";
}
$media->save();
$im->destroy();
// ---- Creation des vignettes de base
$this->createSysThumb($media);
// ---- Creation des vignettes en lien avec le sujet du média
if (isset($sujet_id)) {
$this->createThumb($media);
}
break;
// * Illustration/Vectorielle (2)
case 'svg':
$media->typemedia_id = 2;
$media->save();
break;
// * Vidéo (3)
case 'mp4':
$media->typemedia_id = 3;
$getID3 = new \getID3();
if ($fileInfo = $getID3->analyze($destinationPath . $filename)) {
$media->largeur = $fileInfo['video']['resolution_x'];
$media->hauteur = $fileInfo['video']['resolution_y'];
$media->duree = $fileInfo['playtime_string'];
}
$media->save();
break;
// * Audio (4)
case 'mp3':
$media->typemedia_id = 4;
$getID3 = new \getID3();
if ($fileInfo = $getID3->analyze($destinationPath . $filename)) {
$media->duree = $fileInfo['playtime_string'];
}
$media->save();
break;
}//end switch
$id = $media->id;
$media = Media::find($id);
// ---- Index dans Elasticsearch
$media = Media::where('id', $media->id)->first();
$media->addToIndex();
// ---- Historique des actions
$historique = new Historique();
if ($user = Auth::user()) {
$historique->user_id = $user->id;
}
$historique->media_id = $media->id;
if ($replaceMediaId == 0) {
$historique->type = "Création";
$historique->description = "Média ajouté";
} else {
$historique->type = "Modification";
$historique->description = "Le média a été remplacé";
}
$historique->save();
$filest = array();
$filest['name'] = $filename;
$filest['uid'] = $uid;
$filest['libelle'] = $media->libelle;
$filest['id'] = $media->id;
$filest['folder'] = $media->folder;
$filest['extension'] = $media->extension;
$filest['typemedia_id'] = $media->typemedia_id;
$filesa['files'][] = $filest;
}//end if
}//end foreach
return $filesa;
}//end if
}
public function storeMediaV2(Request $request)
{
$uid = $request->input('uid');
$sujet_id = $request->input('sujet_id');
$dossier_id = $request->input('dossier_id');
$replaceMediaId = $request->input('replaceMediaId');
if ($dossier_id == 0) {
$dossier_id = null;
}
$filesa = [];
$acceptFileTypes = array('gif','jpeg', 'jpg','png','mp4','mp3','psd','ai','svg','pdf');
if (!$uid) {
$uid = Str::uuid();
}
$file = $request->file('files');
if (!empty($file)) {
$extension = strtolower($file->getClientOriginalExtension());
$originalName = str_replace("." . $extension, "", $file->getClientOriginalName());
if (!in_array($extension, $acceptFileTypes)) {
return array("false");
}
if (!in_array($extension, $acceptFileTypes)) {
return array("error" => "Ce type de fichier n'est pas accepté.");
}
// * check the error status
if ($file->getError() != 0) {
Log::error('error ' . $file->getError() . ' in file ' . $request->resumableFilename);
}
$temp_dir = 'uploads';
/**
* init the destination file (format <filename.ext>.part<#chunk>
* the file is stored in a temporary directory
*/
if (isset($request->resumableIdentifier) && trim($request->resumableIdentifier) != '') {
$temp_dir .= "/{$request->resumableIdentifier}";
}
$dest_file = "{$temp_dir}/{$request->resumableFilename}.part{$request->resumableChunkNumber}";
// * create the temporary directory
if (!is_dir($temp_dir)) {
mkdir($temp_dir, 0777, true);
}
// * move the temporary file
if (!move_uploaded_file($file->getPathname(), $dest_file)) {
Log::error(
//phpcs:ignore Generic.Files.LineLength.TooLong
"Error saving (move_uploaded_file) chunk $request->resumableChunkNumber for file $request->resumableFilename"
);
} else {
$filename = $uid . '.' . $extension;
// * check if all the parts present, and create the final destination file
$isLast = $this->createFileFromChunks(
$temp_dir,
$request->resumableFilename,
$request->resumableChunkSize,
$request->resumableTotalSize,
$request->resumableTotalChunks,
$filename
);
if ($isLast) {
$destinationPath = $this->getMediaFolder() . "/";
// * si on upload un média pour remplacer un fichier par un autre
if ($replaceMediaId != 0) {
// * on récupère le média à modifier
/** @var \App\Models\Media $media */
$media = Media::where('id', $replaceMediaId)->firstOrFail();
// * On déplace le fichier dans le répertoire des médias
Storage::move("uploads/" . $filename, $destinationPath . $filename);
// * supprime les fichiers médias stockés sur disque
$filesfF = Storage::files($media->folder . "/");
$filepath = preg_quote($media->folder . $media->uid, '/');
$matchingFiles = preg_grep('/^' . $filepath . '/', $filesfF);
Storage::delete($matchingFiles);
$media->isDefault = 0;
$media->save();
} else {
// * On déplace le fichier dans le répertoire des médias
Storage::move("uploads/" . $filename, $destinationPath . $filename);
// * on créé un média en bdd
$media = new Media();
$media->dossier_id = $dossier_id;
$media->sujet_id = $sujet_id;
// * Par défaut FR
$media->langue_id = 1;
// * Par défaut propriété de la marque
$media->copyright_id = 3;
}//end if
$media->extension = $extension;
$media->folder = $destinationPath;
if ($replaceMediaId == 0) {
$media->libelle = mb_substr($originalName, 0, 50, "UTF-8");
$media->created_by = Auth::user()->id;
}
$media->uid = $uid;
$media->taille = $this->formatBytes($this->getFileSize($destinationPath . $filename));
switch ($extension) {
// * Photo (1)
case 'gif':
case 'jpeg':
case 'jpg':
case 'png':
case 'ai':
case 'pdf':
case 'psd':
$media->typemedia_id = 1;
$im = new \imagick($destinationPath . $filename);
if (in_array($extension, array("pdf", "ai", "psd", "gif"))) {
$im->setIteratorIndex(0);
}
$resolutions = $im->getImageResolution();
$media->resolution = round($resolutions['x'] * 2.54);
$imageprops = $im->getImageGeometry();
$media->largeur = $imageprops['width'];
$media->hauteur = $imageprops['height'];
if ($media->resolution != 0) {
$media->largeur_mm = ceil(($media->largeur * 2.54 / $media->resolution) * 10);
$media->hauteur_mm = ceil(($media->hauteur * 2.54 / $media->resolution) * 10);
} else {
$media->largeur_mm = "";
$media->hauteur_mm = "";
}
$media->save();
$im->destroy();
// ---- Creation des vignettes de base
$this->createSysThumb($media);
// ---- Creation des vignettes en lien avec le sujet du média
if (isset($sujet_id)) {
$this->createThumb($media);
}
break;
// * Illustration/Vectorielle (2)
case 'svg':
$media->typemedia_id = 2;
$media->save();
break;
// * Vidéo (3)
case 'mp4':
$media->typemedia_id = 3;
$getID3 = new \getID3();
if ($fileInfo = $getID3->analyze($destinationPath . $filename)) {
$media->largeur = $fileInfo['video']['resolution_x'];
$media->hauteur = $fileInfo['video']['resolution_y'];
$media->duree = $fileInfo['playtime_string'];
}
$media->save();
break;
// * Audio (4)
case 'mp3':
$media->typemedia_id = 4;
$getID3 = new \getID3();
if ($fileInfo = $getID3->analyze($destinationPath . $filename)) {
$media->duree = $fileInfo['playtime_string'];
}
$media->save();
break;
}//end switch
$id = $media->id;
$media = Media::find($id);
// ---- Index dans Elasticsearch
$media = Media::where('id', $media->id)->first();
$media->addToIndex();
// ---- Historique des actions
$historique = new Historique();
if ($user = Auth::user()) {
$historique->user_id = $user->id;
}
$historique->media_id = $media->id;
if ($replaceMediaId == 0) {
$historique->type = "Création";
$historique->description = "Média ajouté";
} else {
$historique->type = "Modification";
$historique->description = "Le média a été remplacé";
}
$historique->save();
return response()->json($media);
}//end if
}//end if
}//end if
]);
}
/**
* Check if all the parts exist, and
* gather all the parts of the file together
* Asynchronous chunked upload file.
*
* @param string $temp_dir The temporary directory holding all the parts of the file.
* @param string $fileName The original file name.
* @param integer $chunkSize Each chunk size (in bytes).
* @param integer $totalSize Original file size (in bytes).
* @param integer $total_files
* @param string $finalName
* @return boolean
* @param \App\Http\Requests\Bo\Ajax\UploadMediaFileRequest $request
* @param \Pion\Laravel\ChunkUpload\Receiver\FileReceiver $receiver
* @return \Illuminate\Http\JsonResponse
* @throws \Pion\Laravel\ChunkUpload\Exceptions\UploadMissingFileException If failed upload.
*/
private function createFileFromChunks(
string $temp_dir,
string $fileName,
int $chunkSize,
int $totalSize,
int $total_files,
string $finalName
): bool {
// * count all the parts of this file
$total_files_on_server_size = 0;
$temp_total = 0;
foreach (scandir($temp_dir) as $file) {
$temp_total = $total_files_on_server_size;
$tempfilesize = filesize($temp_dir . '/' . $file);
$total_files_on_server_size = $temp_total + $tempfilesize;
}
// * check that all the parts are present
// * If the Size of all the chunks on the server is equal to the size of the file uploaded.
if ($total_files_on_server_size >= $totalSize) {
// * create the final destination file
if (($fp = fopen("uploads/{$finalName}", 'w')) !== false) {
for ($i = 1; $i <= $total_files; $i++) {
fwrite($fp, file_get_contents("{$temp_dir}/{$fileName}.part{$i}"));
}
fclose($fp);
} else {
Log::error('cannot create the destination file');
return false;
}
public function uploadMediaFileIntoDepot(
UploadMediaFileRequest $request,
FileReceiver $receiver,
): JsonResponse {
/** @var \App\Models\Dossier */
$dossier = Dossier::where('id', intval($request->dossier_id))->firstOrFail();
// * rename the temporary directory (to avoid access from other
// * concurrent chunks uploads) and than delete it
if (rename($temp_dir, $temp_dir . '_UNUSED')) {
$this->rrmdir($temp_dir . '_UNUSED');
} else {
$this->rrmdir($temp_dir);
}
return true;
}//end if
return false;
// Check if the upload is success, throw exception or return response you need.
if ($receiver->isUploaded() === false) {
throw new UploadMissingFileException();
}
// Receive the file.
$save = $receiver->receive();
// Check if the upload has finished (in chunk mode it will send smaller files).
if ($save->isFinished()) {
/** @var \App\Models\User */
$user = auth()->user();
$uplodedFile = $save->getFile();
/** @throws \Illuminate\Validation\ValidationException */
$this->validateUploadedFile($uplodedFile);
/** @var \App\Models\Media */
$media = Media::whereId($request->media_id)
->whereHas('dossier', function ($q) use ($dossier) {
$q->whereId($dossier->id);
})->firstOrNew();
// Save the file and return any response you need.
return $this->createOrUpdateMedia($user, $uplodedFile, $media, $dossier);
}
// We are in chunk mode, lets send the current progress.
/** @var AbstractHandler $handler */
$handler = $save->handler();
return response()->json([
'done' => $handler->getPercentageDone()
]);
}
/**
* Delete a directory RECURSIVELY
* Asynchronous chunked upload file.
*
* @param string $dir Directory path.
* @param \App\Http\Requests\Bo\Ajax\UploadMediaFileRequest $request
* @param \Pion\Laravel\ChunkUpload\Receiver\FileReceiver $receiver
* @param \App\Models\Sujet $sujet
* @param \App\Models\Dossier $dossier
* @return \Illuminate\Http\JsonResponse
* @throws \Pion\Laravel\ChunkUpload\Exceptions\UploadMissingFileException If failed upload.
*/
public function uploadMediaFile(
UploadMediaFileRequest $request,
FileReceiver $receiver,
Sujet $sujet,
Dossier $dossier
): JsonResponse {
// Check if the upload is success, throw exception or return response you need.
if ($receiver->isUploaded() === false) {
throw new UploadMissingFileException();
}
// Receive the file.
$save = $receiver->receive();
// Check if the upload has finished (in chunk mode it will send smaller files).
if ($save->isFinished()) {
/** @var \App\Models\User */
$user = auth()->user();
$uplodedFile = $save->getFile();
/** @throws \Illuminate\Validation\ValidationException */
$this->validateUploadedFile($uplodedFile);
/** @var \App\Models\Media */
$media = Media::whereId($request->media_id)
->whereHas('sujet', function ($q) use ($sujet) {
$q->whereId($sujet->id);
})->whereHas('dossier', function ($q) use ($dossier) {
$q->whereId($dossier->id);
})->firstOrNew();
// Save the file and return any response you need.
return $this->createOrUpdateMedia($user, $uplodedFile, $media, $dossier, $sujet);
}
// We are in chunk mode, lets send the current progress.
/** @var AbstractHandler $handler */
$handler = $save->handler();
return response()->json([
'done' => $handler->getPercentageDone()
]);
}
/**
* Validate uploaded file
*
* @param \Illuminate\Http\UploadedFile $file
* @return void
* @link http://php.net/manual/en/function.rmdir.php
* @throws \Illuminate\Validation\ValidationException If uploaded file is not valid.
*/
private function rrmdir(string $dir): void
private function validateUploadedFile(UploadedFile $file)
{
if (is_dir($dir)) {
$objects = scandir($dir);
foreach ($objects as $object) {
if ($object != "." && $object != "..") {
if (filetype($dir . "/" . $object) == "dir") {
$this->rrmdir($dir . "/" . $object);
} else {
unlink($dir . "/" . $object);
}
}
}
reset($objects);
rmdir($dir);
Validator::make([
'file' => $file
], [
'file' => 'required|file|mimes:gif,jpeg,jpg,png,mp4,mp3,psd,ai,svg,pdf'
], [
'files.mimes' => trans('Ce type de fichier n\'est pas accepté.')
])->validate();
$this->validateExtension($file->getClientOriginalExtension());
}
/**
* Validate file extension matches allowed extensions enum
*
* @param string $extension
* @return void
*/
private function validateExtension(string $extension)
{
if (!\is_null(MediaExtension::tryFrom($extension))) {
ValidationException::withMessages([
'file' => trans('Ce type de fichier n\'est pas accepté.')
]);
}
}
/**
* Create or update media
*
* @param \App\Models\User $user
* @param \Illuminate\Http\UploadedFile $file
* @param \App\Models\Media $media
* @param \App\Models\Dossier $dossier
* @param \App\Models\Sujet|null $sujet
* @return \Illuminate\Http\JsonResponse
* @throws \Illuminate\Validation\ValidationException If $subject is missing and folder
* is not a system folder (Dossier dépot).
* @phpcs:disable Generic.Metrics.CyclomaticComplexity.TooHigh
* (switch) .
*/
private function createOrUpdateMedia(
User $user,
UploadedFile $file,
Media $media,
Dossier $dossier,
Sujet|null $sujet = null
): JsonResponse {
// phpcs:enable
return DB::transaction(function () use ($user, $file, $media, $dossier, $sujet) {
if (!$dossier->system and !$sujet) {
throw ValidationException::withMessages([
'file' => 'Cannot put media inside a non system folder (depot) without a subject'
]);
}
/** @var \Illuminate\Filesystem\FilesystemAdapter */
$storage = Storage::disk('media');
$isNewMedia = !$media->exists;
$mediaFolderName = $this->getCurentMediaFolderName();
// * File size
$fileSize = $file->getSize();
$sanitizedFileName = ToolboxHelper::sanitizeFileName($file->getClientOriginalName());
/** @var string */
$sanitizedFileBasename = \pathinfo($sanitizedFileName, \PATHINFO_BASENAME);
/** @var string */
$sanitizedFileExtension = \pathinfo($sanitizedFileName, \PATHINFO_EXTENSION);
// * Validate Extension
/** @throws \ValueError If value is not defined in enum */
$mediaExtension = MediaExtension::from($sanitizedFileExtension);
if (!$isNewMedia) {
// Supprimer les vielles images.
$media->deleteFilesOnAllPath();
}
// * New folder attribution
$media->folder = $mediaFolderName;
// * New Image, New uuid.
$media->uid = Str::uuid();
// * New Image extension
$media->extension = $mediaExtension;
// * New Image size
$media->taille = $fileSize ? $fileSize : 0;
// * Le media n'est pas une image par défaut.
$media->isDefault = false;
// TODO: Supprimer old fichier dans le cas d'un update.
// * On déplace le fichier dans le répertoire des médias.
/** @throws \FileException */
$file->move($storage->path($media->folder), "{$media->uid}.{$media->extension->value}");
// * Si on upload un média pour remplacer un fichier par un autre
if ($isNewMedia) {
$media->libelle = Str::limit($sanitizedFileBasename, 50, '');
$media->owner()->associate($user);
$media->dossier()->associate($dossier);
$media->sujet()->associate($sujet);
// * Par défaut FR
$media->langue()->associate(Langue::getDefaultLang());
// * Par défaut propriété de la marque
$media->copyright()->associate(Copyright::getBrandCopyright());
$media->etiquette()->associate(Etiquette::getDefaultEtiquette());
}
switch ($media->extension) {
case MediaExtension::gif:
case MediaExtension::jpeg:
case MediaExtension::jpg:
case MediaExtension::png:
case MediaExtension::ai:
case MediaExtension::pdf:
case MediaExtension::psd:
$dimensions = ToolboxHelper::getImageDimensions($media->full_path);
if ($dimensions) {
$media->resolution = $dimensions['resolutionX'];
$media->largeur = $dimensions['width'];
$media->hauteur = $dimensions['height'];
$media->largeur_mm = !empty($media->resolution) ? ceil($media->largeur * 10) : 0;
$media->hauteur_mm = !empty($media->resolution) ? ceil($media->hauteur * 10) : 0;
}
// ---- Creation des vignettes de base
$media->createThumbnail();
// ---- Creation des vignettes en lien avec le sujet du média
$media->createSubjectThumbnails();
break;
case MediaExtension::mp4:
if ($dimensions = ToolboxHelper::getId3VideoDimensions($media->full_path)) {
$media->largeur = $dimensions['width'];
$media->hauteur = $dimensions['height'];
}
// Fall-through .
case MediaExtension::mp3:
$media->duree = ToolboxHelper::getId3Playtime($media->full_path);
break;
} //end switch
$media->typeMedia()->associate(TypeMedia::getMediaType($media->extension));
$media->saveOrFail();
// * Get props inserted by DB.
$media->refresh();
return response()->json($media);
});
}
}

View file

@ -41,7 +41,7 @@ class UserController extends Controller
$localUser->authorizeRoles(config('roles.const.ADMIN'));
$roles = config('roles.label');
$marques = Marque::orderBy('libMarq', 'asc')->get();
$sujets = Sujet::where('sujet_dam', 1)->orderBy('libelle', 'asc')->get();
$sujets = Sujet::where('sujet_dam', true)->orderBy('libelle', 'asc')->get();
return view('users.create')->with([
'roles' => $roles, 'marques' => $marques,
'sujets' => $sujets
@ -188,7 +188,7 @@ class UserController extends Controller
$userMarques = $user->marques;
$marques = Marque::orderBy('libMarq', 'asc')->get();
$userSujets = $user->sujets;
$sujets = Sujet::where('sujet_dam', 1)->orderBy('libelle', 'asc')->get();
$sujets = Sujet::where('sujet_dam', true)->orderBy('libelle', 'asc')->get();
$users = User::select(['id', 'email'])->whereIn('role', [
config('roles.const.ADMIN'), config('roles.const.CONTRIBUTEUR'),
config('roles.const.REDACTEUR')

View file

@ -14,7 +14,7 @@ class Kernel extends HttpKernel
* @var array<int, class-string|string>
*/
protected $middleware = [
// \App\Http\Middleware\TrustHosts::class,
\App\Http\Middleware\TrustHosts::class,
\App\Http\Middleware\TrustProxies::class,
\Illuminate\Http\Middleware\HandleCors::class,
\App\Http\Middleware\PreventRequestsDuringMaintenance::class,
@ -31,6 +31,7 @@ class Kernel extends HttpKernel
*/
protected $middlewareGroups = [
'web' => [
'htmlsanitize',
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
@ -41,7 +42,6 @@ class Kernel extends HttpKernel
'api' => [
'throttle:api',
// \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
@ -64,5 +64,6 @@ class Kernel extends HttpKernel
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
'htmlsanitize' => \App\Http\Middleware\HtmlSanitizer::class,
];
}

View file

@ -0,0 +1,43 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Http\Request;
class HtmlSanitizer
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param mixed ...$params
* @return mixed
*/
public function handle(Request $request, \Closure $next, mixed ...$params)
{
$inputs = $request->all();
array_walk_recursive($inputs, function (&$input, $name) use ($params) {
if (!is_string($input)) {
return;
}
if (in_array($name, $params)) {
// ? Is a json input ?
if ($isJson = \json_decode($input, true) and is_array($isJson)) {
// ! Decode each json field recursive.
\array_walk_recursive($isJson, function (&$item) {
if (\is_string($item)) {
$item = clean($item);
}
});
} else {
$input = clean($input);
}
} else {
$input = strip_tags($input);
}
});
$request->merge($inputs);
return $next($request);
}
}

View file

@ -3,7 +3,6 @@
namespace App\Http\Middleware;
use App\Providers\RouteServiceProvider;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
@ -12,13 +11,14 @@ class RedirectIfAuthenticated
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
* @param string|null ...$guards
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null ...$guards
* @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
*/
public function handle(Request $request, Closure $next, ...$guards)
public function handle(Request $request, \Closure $next, ...$guards)
{
/** @var array<string|null> */
$guards = empty($guards) ? [null] : $guards;
foreach ($guards as $guard) {

View file

@ -1,10 +1,10 @@
<?php
namespace App\Http\Requests\Bo;
namespace App\Http\Requests\Bo\Ajax;
use Illuminate\Foundation\Http\FormRequest;
class AjaxAddMediasBasketRequest extends FormRequest
class AddMediasBasketRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
@ -13,7 +13,7 @@ class AjaxAddMediasBasketRequest extends FormRequest
*/
public function authorize()
{
return auth()->check();
return auth()->check() and $this->ajax();
}
/**
@ -25,8 +25,8 @@ class AjaxAddMediasBasketRequest extends FormRequest
{
return [
'panier_id' => 'required|exists:paniers,id,deleted_at,NULL',
'medias' => 'required|array',
'medias.*' => 'required|exists:medias,id,deleted_at,NULL'
'mediaList' => 'required|array',
'mediaList.*' => 'required|exists:media,id,deleted_at,NULL'
];
}
}

View file

@ -0,0 +1,33 @@
<?php
namespace App\Http\Requests\Bo\Ajax;
use Illuminate\Foundation\Http\FormRequest;
class ApplyStickerRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return boolean
*/
public function authorize(): bool
{
return auth()->check();
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, mixed>
*/
public function rules(): array
{
return [
'etiquette_id' => 'required|exists:etiquettes,etiquette_id',
'mediaList' => 'required|array',
'mediaList.*' => 'array|min:0',
'mediaList.*.id' => 'required|exists:media,id',
];
}
}

View file

@ -0,0 +1,43 @@
<?php
namespace App\Http\Requests\Bo\Ajax;
use App\Models\Media;
use Illuminate\Foundation\Http\FormRequest;
class CheckRefKeyRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return boolean
*/
public function authorize()
{
return \auth()->check() and $this->ajax();
}
/**
* Prepare the data for validation.
*
* @return void
*/
protected function prepareForValidation()
{
$this->merge([
'media' => Media::where('id', $this->media_id)->first()
]);
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, mixed>
*/
public function rules()
{
return [
'media_id' => 'required|exists:media,id,deleted_at,NULL'
];
}
}

View file

@ -1,11 +1,11 @@
<?php
namespace App\Http\Requests\Bo;
namespace App\Http\Requests\Bo\Ajax;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Carbon;
class AjaxCreateBasketRequest extends FormRequest
class CreateBasketRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
@ -18,7 +18,7 @@ class AjaxCreateBasketRequest extends FormRequest
'title' => $this->title ??
sprintf('Panier du %s', Carbon::now()->format('d/m/Y'))
]);
return auth()->check();
return auth()->check() and $this->ajax();
}
/**

View file

@ -0,0 +1,31 @@
<?php
namespace App\Http\Requests\Bo\Ajax;
use Illuminate\Foundation\Http\FormRequest;
class DeleteMediaRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return boolean
*/
public function authorize()
{
return auth()->check() and $this->ajax();
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'mediaList' => 'required|array',
'mediaList.*' => 'required|exists:media,id,deleted_at,NULL'
];
}
}

View file

@ -1,10 +1,10 @@
<?php
namespace App\Http\Requests\Bo;
namespace App\Http\Requests\Bo\Ajax;
use Illuminate\Foundation\Http\FormRequest;
class AjaxDestroyBasketRequest extends FormRequest
class DestroyBasketRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
@ -13,7 +13,7 @@ class AjaxDestroyBasketRequest extends FormRequest
*/
public function authorize()
{
return auth()->check();
return auth()->check() and $this->ajax();
}
/**

View file

@ -0,0 +1,30 @@
<?php
namespace App\Http\Requests\Bo\Ajax;
use Illuminate\Foundation\Http\FormRequest;
class FetchFoldersRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return boolean
*/
public function authorize(): bool
{
return auth()->check() and $this->ajax();
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, mixed>
*/
public function rules()
{
return [
'sujetId' => 'required|exists:sujets,codeSujet'
];
}
}

View file

@ -0,0 +1,30 @@
<?php
namespace App\Http\Requests\Bo\Ajax;
use Illuminate\Foundation\Http\FormRequest;
class GetArticleRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return boolean
*/
public function authorize(): bool
{
return \auth()->check();
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, mixed>
*/
public function rules()
{
return [
'arcadia_id' => 'required|exists:articles,noArt'
];
}
}

View file

@ -0,0 +1,30 @@
<?php
namespace App\Http\Requests\Bo\Ajax;
use Illuminate\Foundation\Http\FormRequest;
class LoadFoldersRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return boolean
*/
public function authorize()
{
return \auth()->check() and $this->ajax();
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, mixed>
*/
public function rules()
{
return [
'sujet_id' => 'required|exists:sujets,codeSujet'
];
}
}

View file

@ -0,0 +1,33 @@
<?php
namespace App\Http\Requests\Bo\Ajax;
use Illuminate\Foundation\Http\FormRequest;
class MoveMediaRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return boolean
*/
public function authorize(): bool
{
return auth()->check() and $this->ajax();
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, mixed>
*/
public function rules()
{
return [
'dossier_id' => 'required|numeric',
'mediaList' => 'required|array',
'mediaList.*' => 'required|array',
'mediaList.*.id' => 'required|exists:media,id',
];
}
}

View file

@ -1,10 +1,10 @@
<?php
namespace App\Http\Requests\Bo;
namespace App\Http\Requests\Bo\Ajax;
use Illuminate\Foundation\Http\FormRequest;
class AjaxRemoveMediasBasketRequest extends FormRequest
class RemoveMediasBasketRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
@ -13,7 +13,7 @@ class AjaxRemoveMediasBasketRequest extends FormRequest
*/
public function authorize()
{
return auth()->check();
return auth()->check() and $this->ajax();
}
/**
@ -25,7 +25,7 @@ class AjaxRemoveMediasBasketRequest extends FormRequest
{
return [
'panier_id' => 'required|exists:paniers,id,deleted_at,NULL',
'media_id' => 'required|exists:medias,id,deleted_at,NULL'
'media_id' => 'required|exists:media,id,deleted_at,NULL'
];
}
}

View file

@ -1,10 +1,10 @@
<?php
namespace App\Http\Requests\Bo;
namespace App\Http\Requests\Bo\Ajax;
use Illuminate\Foundation\Http\FormRequest;
class AjaxSaveBasketPropsRequest extends FormRequest
class SaveBasketPropsRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
@ -16,7 +16,7 @@ class AjaxSaveBasketPropsRequest extends FormRequest
$this->merge([
'statut' => $this->statut ? true : false
]);
return \auth()->check();
return auth()->check() and $this->ajax();
}
/**

View file

@ -0,0 +1,47 @@
<?php
namespace App\Http\Requests\Bo\Ajax;
use App\Enums\ContactType;
use App\Rules\EnumIsValidRule;
use Illuminate\Foundation\Http\FormRequest;
class SendContactMessageRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return boolean
*/
public function authorize()
{
return auth()->check() and $this->ajax();
}
/**
* Prepare the data for validation.
*
* @return void
*/
protected function prepareForValidation()
{
$this->merge([
'url' => strval($this->url),
'type' => intval($this->type)
]);
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, mixed>
*/
public function rules()
{
return [
'type' => ['required', new EnumIsValidRule(ContactType::class)],
'url' => 'nullable|url',
'message' => 'required|string|min:20'
];
}
}

View file

@ -0,0 +1,30 @@
<?php
namespace App\Http\Requests\Bo\Ajax;
use Illuminate\Foundation\Http\FormRequest;
class StoreMediaFileRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return boolean
*/
public function authorize()
{
return auth()->check() and $this->ajax();
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, mixed>
*/
public function rules()
{
return [
'media_id' => 'nullable|exists:media,id'
];
}
}

View file

@ -0,0 +1,108 @@
<?php
namespace App\Http\Requests\Bo\Ajax;
use Illuminate\Foundation\Http\FormRequest;
class UpdateMediaRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return boolean
*/
public function authorize(): bool
{
return auth()->check() and $this->ajax();
}
/**
* Prepare the data for validation.
*
* @return void
*/
protected function prepareForValidation()
{
$this->merge([
'tags' => $this->tags ?? [],
'marques' => $this->marques ?? [],
'societes' => $this->societes ?? []
]);
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, mixed>
*/
public function rules()
{
$rules = [
'statut' => 'required|numeric|in:0,1,2',
'version' => 'required|numeric|min:1',
'type_vue_id' => 'required|exists:type_vues,codeTypevue',
'variante_id' => 'required|exists:variantes,codeVariante',
'langue_id' => 'required|exists:langues,langue_id',
];
// ? Est lié à arcadia ?
if ($this->media->arcadia_id) {
// Ne pas autoriser brouillon .
$rules['statut'] = 'required|numeric|in:1,2';
unset($rules['version']);
unset($rules['type_vue_id']);
unset($rules['variante_id']);
unset($rules['langue_id']);
}
// Marque.
if ($this->sujet_id == 2) {
$rules['marques'] = 'present|array|min:0';
$rules['marques.*'] = 'array';
$rules['marques.*.codMarq'] = 'exists:marques,codMarq';
}
// Sociétés.
if ($this->sujet_id == 4) {
$rules['societes'] = 'present|array|min:0';
$rules['societes.*'] = 'array';
$rules['societes.*.id'] = 'exists:societes,id';
}
return \array_merge($rules, [
'libelle' => 'required|string|min:2|max:50',
'commentaire' => 'nullable|string|min:2',
'copyright_id' => 'required|exists:copyrights,copyright_id',
// Tags.
'tags' => 'present|array|min:0',
'tags.*.libelle' => 'min:2|max:50',
'etiquette_id' => 'required|exists:etiquettes,etiquette_id',
]);
}
/**
* Get custom attributes for validator errors.
*
* @return array<string,string>
*/
public function attributes(): array
{
return [
'libelle' => trans('libelle'),
'commentaire' => trans('commentaire'),
'societes' => trans('societes'),
'societes.*' => trans('societes'),
'societes.*.id' => trans('societes'),
'marques' => trans('marques'),
'marques.*' => trans('marques'),
'marques.*.codMarq' => trans('marques'),
'copyright_id' => trans('copyright'),
'etiquette_id' => trans('etiquette'),
'type_vue_id' => trans('type de vue'),
'variante_id' => trans('type de variante'),
'tags' => trans('nuage de tags'),
'tags.*.libelle' => trans('libellé dans le nuage de tags'),
];
}
}

View file

@ -0,0 +1,31 @@
<?php
namespace App\Http\Requests\Bo\Ajax;
use Illuminate\Foundation\Http\FormRequest;
class UploadMediaFileRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return boolean
*/
public function authorize()
{
return auth()->check();
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, mixed>
*/
public function rules()
{
return [
'media_id' => 'nullable|exists:media,id',
'dossier_id' => 'sometimes|exists:dossiers,id'
];
}
}

View file

@ -4,14 +4,14 @@ namespace App\Http\Requests\Bo;
use Illuminate\Foundation\Http\FormRequest;
class AjaxDeleteMediaRequest extends FormRequest
class DownloadMediaRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return boolean
*/
public function authorize()
public function authorize(): bool
{
return auth()->check();
}
@ -19,13 +19,13 @@ class AjaxDeleteMediaRequest extends FormRequest
/**
* Get the validation rules that apply to the request.
*
* @return array
* @return array<string, mixed>
*/
public function rules()
{
return [
'medias' => 'required|array',
'medias.*' => 'exists:medias,id,deleted_at,NULL'
'mediaList' => 'required|array',
'mediaList.*' => 'required|exists:media,id',
];
}
}

View file

@ -0,0 +1,31 @@
<?php
namespace App\Http\Requests\Bo\Folders;
use Illuminate\Foundation\Http\FormRequest;
class StoreDepotFolderRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return boolean
*/
public function authorize(): bool
{
return auth()->check();
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, mixed>
*/
public function rules()
{
return [
'libelle' => 'required|string|min:4|max:255|unique:dossiers,libelle',
'description' => 'nullable|string|min:4'
];
}
}

View file

@ -0,0 +1,56 @@
<?php
namespace App\Http\Requests\Bo\Folders;
use Illuminate\Foundation\Http\FormRequest;
class StoreFolderRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return boolean
*/
public function authorize(): bool
{
return auth()->check();
}
/**
* Prepare the data for validation.
*
* @return void
*/
protected function prepareForValidation()
{
$this->merge([
'sub' => $this->sub ? true : false,
'is_private' => $this->status ? true : false,
'marques' => !$this->marques ? null : \explode(',', \strval($this->marques))
]);
if ($this->sub) {
$this->merge([
'is_private' => false
]);
}
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, mixed>
*/
public function rules()
{
return [
'parent_id' => 'sometimes|exists:dossiers,id',
'libelle' => 'required|string|min:4|max:255|unique:dossiers,libelle',
'description' => 'nullable|string|min:4',
'sujet' => 'required_unless:sub,true|exists:sujets,codeSujet',
'is_private' => 'required|boolean',
'marques' => 'nullable|array',
'marques.*' => 'required|exists:marques,codMarq',
'sub' => 'required|boolean'
];
}
}

View file

@ -0,0 +1,20 @@
<?php
namespace App\Http\Requests\Bo\Folders;
class UpdateFolderRequest extends StoreFolderRequest
{
/**
* Get the validation rules that apply to the request.
*
* @return array<string, mixed>
*/
public function rules()
{
$rules = \array_merge(parent::rules(), [
'libelle' => 'required|string|min:4|max:255|unique:dossiers,libelle,' . $this->dossier->id,
]);
unset($rules['parent_id']);
return $rules;
}
}

View file

@ -0,0 +1,95 @@
<?php
namespace App\Http\Requests\Bo;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Validator;
class LoadMediaRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return boolean
*/
public function authorize(): bool
{
return auth()->check();
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, mixed>
*/
public function rules()
{
return [
'sujet' => 'required|exists:sujets,codeSujet',
'offset' => 'sometimes|numeric',
'limit' => 'sometimes|numeric|gt:0|lte:50',
'folder' => 'sometimes|numeric',
'filters' => 'sometimes|array',
'filters.*' => 'required|array',
'filters.*.legend' => 'required|string',
'filters.*.libelle' => 'required|string',
'filters.*.order' => 'sometimes|in:desc,asc',
'filters.*.type' => 'required|in:order,dossier_id,type_media_id,type_vue_id,etiquette_id,arcadia_id,search',
'filters.*.value' => [
'nullable', function ($attribute, $value, $fail) {
$index = intval(collect(\explode('.', $attribute))->get(1));
$filterType = \strval(collect(collect($this->filters)->get($index))->get('type'));
switch ($filterType) {
case 'type_vue_id':
$attribute = \str_replace('.', '_', $attribute);
Validator::validate([$attribute => $value], [
$attribute => 'required|array',
"$attribute.*" => 'required|array',
"$attribute.*.codeTypevue" => 'required|exists:type_vues,codeTypevue',
]);
return;
case 'type_media_id':
$attribute = \str_replace('.', '_', $attribute);
Validator::validate([$attribute => $value], [
$attribute => 'required|array',
"$attribute.*" => 'required|array',
"$attribute.*.codeTypemedia" => 'required|exists:type_media,codeTypemedia',
]);
return;
case 'etiquette_id':
$attribute = \str_replace('.', '_', $attribute);
Validator::validate([$attribute => $value], [
$attribute => 'required|array',
"$attribute.*" => 'required|array',
"$attribute.*.etiquette_id" => 'required|exists:etiquettes,etiquette_id',
]);
return;
case 'dossier_id':
$attribute = \str_replace('.', '_', $attribute);
if (\intval($value) === 0) {
return;
}
Validator::validate([$attribute => $value], [
$attribute => 'required|exists:dossiers,id'
]);
return;
case 'order':
if (!\in_array($value, ['created_at', 'updated_at', 'version', 'libelle.keyword'])) {
$fail("Unhandled filter type order for '$value'");
}
return;
case 'search':
$attribute = \str_replace('.', '_', $attribute);
Validator::validate([$attribute => $value], [
$attribute => 'required|string'
]);
return;
default:
$fail("Unhandled filter type '$filterType'");
return;
} //end switch
}
],
];
}
}

View file

@ -0,0 +1,37 @@
<?php
namespace App\Http\Requests\Bo;
use Illuminate\Foundation\Http\FormRequest;
class ShowInterfaceRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return boolean
*/
public function authorize(): bool
{
return auth()->check();
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, mixed>
*/
public function rules()
{
return [
// * Dossier
'd' => 'sometimes|numeric',
// * Sujet
's' => 'sometimes|exists:sujets,codeSujet',
// * text search
't' => 'sometimes|string',
// * Recherche
'r' => 'sometimes|exists:recherches,id'
];
}
}

View file

@ -0,0 +1,30 @@
<?php
namespace App\Http\Resources;
use App\Models\Dossier;
use Illuminate\Http\Resources\Json\ResourceCollection as JsonResourceCollection;
class NestedDossiersListResource extends JsonResourceCollection
{
/**
* Transform the resource into an array.
*
* @param mixed $request
* @return array
*/
// phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundInExtendedClass, Squiz.Commenting.FunctionComment.Missing
public function toArray($request)
{
return $this->collection->map(function (Dossier $dossier) {
return [
'id' => $dossier->id,
'libelle' => $dossier->libelle,
'system' => $dossier->system,
'favoris' => $dossier->favoris,
'mediacount' => $dossier->mediacount,
'sousdossiers' => new self($dossier->sousdossiers)
];
});
}
}

View file

@ -1,198 +0,0 @@
<?php
namespace App\Http\Traits;
use App\Models\Format;
use App\Scopes\SystemScope;
use DOMDocument;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
trait ArcadiaLink
{
public static function checkRequiredValues($media)
{
$required = ['sujet_id', 'typemedia_id', 'typevue_id', 'variante_id', 'langue_id', 'version'];
foreach ($required as $v) {
if ($media->$v === null) {
return false;
}
}
return true;
}
public static function create($media)
{
if (!self::checkRequiredValues($media)) {
return;
}
$media->isLocked = 1;
$media->save();
self::convert(self::getXML($media, "C"), $media);
}
public static function update($media)
{
if ($media->arcadia_id === null) {
return;
}
if (!self::checkRequiredValues($media)) {
return;
}
$media->isLocked = 1;
$media->save();
self::convert(self::getXML($media, "M"), $media);
}
public static function delete($media)
{
if ($media->arcadia_id === null) {
return;
}
if (!self::checkRequiredValues($media)) {
return;
}
$media->isLocked = 1;
$media->save();
self::convert(self::getXML($media, "S"), $media);
}
public static function reactivate($media)
{
if ($media->arcadia_id === null) {
return;
}
if (!self::checkRequiredValues($media)) {
return;
}
$media->isLocked = 1;
$media->save();
self::convert(self::getXML($media, "R"), $media);
}
private static function convert($xml, $media)
{
$uid = sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x', mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0x0fff) | 0x4000, mt_rand(0, 0x3fff) | 0x8000, mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff));
Storage::disk('arcadia_link_s')->put("$uid.xml", $xml);
self::compress($uid, $media);
}
private static function compress($uid, $media)
{
try {
$zip_file = storage_path('arcadia_link/send') . "/$media->id-$uid.zip";
$zip = new \ZipArchive();
$zip->open($zip_file, \ZipArchive::CREATE | \ZipArchive::OVERWRITE);
$zip->addFile(storage_path('arcadia_link/send') . "/$uid.xml", 'media.xml');
$zip->addFile(public_path() . "/$media->folder$media->uid.$media->extension", "$media->uid.$media->extension");
$zip->close();
unset($zip);
unlink(storage_path('arcadia_link/send') . "/$uid.xml");
// On insert dans la table de supervision
$s = new \App\Models\ArcadiaLink();
$s->media_id = $media->id;
if ($media->arcadia_id !== null) {
$s->arcadia_id = $media->arcadia_id;
}
$s->filename = "$media->id-$uid.zip";
$s->save();
} catch (Exception $e) {
// echo "Exception : " . $e;
// TODO : Envoi mail Log
Log::emergency("Erreur création .zip : $e (Traits/ArcadiaLink)");
}//end try
}
private static function getXML($media, $mouvement)
{
$refKey = self::getRefKey($media);
$formats = self::getFormats();
$dom = new DOMDocument('1.0', 'UTF-8');
$dom->formatOutput = true;
$root = $dom->createElement('MEDIA_VISUEL');
$dom->appendChild($root);
$root->appendChild($dom->createElement('codeArcadia'))->appendChild($dom->createCDATASection("$media->arcadia_id"));
$root->appendChild($dom->createElement('code_DAM'))->appendChild($dom->createCDATASection("$media->id"));
$root->appendChild($dom->createElement('TypeMouvement'))->appendChild($dom->createCDATASection("$mouvement"));
$cleRef = $root->appendChild($dom->createElement('cle_Referentiel'));
foreach ($refKey as $k) {
if ($media->sujet_id === 1) {
$cleRef->appendChild($dom->createElement('id'))->appendChild($dom->createCDATASection("$k->noArt"));
} elseif ($media->sujet_id === 2) {
$cleRef->appendChild($dom->createElement('id'))->appendChild($dom->createCDATASection("$k->codMarq"));
} elseif ($media->sujet_id === 4) {
$cleRef->appendChild($dom->createElement('id'))->appendChild($dom->createCDATASection("$k->id"));
}
}
$root->appendChild($dom->createElement('libExtension'))->appendChild($dom->createCDATASection("$media->extension"));
$root->appendChild($dom->createElement('nbPxLargeur'))->appendChild($dom->createCDATASection("$media->largeur"));
$root->appendChild($dom->createElement('largeurMm'))->appendChild($dom->createCDATASection("$media->largeur_mm"));
$root->appendChild($dom->createElement('nbPxHauteur'))->appendChild($dom->createCDATASection("$media->hauteur"));
$root->appendChild($dom->createElement('hauteurMm'))->appendChild($dom->createCDATASection("$media->hauteur_mm"));
$root->appendChild($dom->createElement('pppLargeur'))->appendChild($dom->createCDATASection("$media->resolution"));
$root->appendChild($dom->createElement('version'))->appendChild($dom->createCDATASection("$media->version"));
$root->appendChild($dom->createElement('codeTypeMedia'))->appendChild($dom->createCDATASection("$media->typemedia_id"));
$root->appendChild($dom->createElement('codeTypeVue'))->appendChild($dom->createCDATASection("$media->typevue_id"));
$root->appendChild($dom->createElement('commentaire'))->appendChild($dom->createCDATASection("$media->commentaire"));
$root->appendChild($dom->createElement('codeSujet'))->appendChild($dom->createCDATASection("$media->sujet_id"));
$root->appendChild($dom->createElement('langue'))->appendChild($dom->createCDATASection("$media->langue_id"));
$root->appendChild($dom->createElement('copyright'))->appendChild($dom->createCDATASection("$media->copyright_id"));
$root->appendChild($dom->createElement('codeVariante'))->appendChild($dom->createCDATASection("$media->variante_id"));
$root->appendChild($dom->createElement('dateCreation'))->appendChild($dom->createCDATASection("$media->created_at"));
$root->appendChild($dom->createElement('dateModification'))->appendChild($dom->createCDATASection("$media->updated_at"));
$root->appendChild($dom->createElement('datePublication'))->appendChild($dom->createCDATASection("$media->published_at"));
$root->appendChild($dom->createElement('libelle'))->appendChild($dom->createCDATASection("$media->libelle"));
$root->appendChild($dom->createElement('NomFichier'))->appendChild($dom->createCDATASection("$media->uid.$media->extension"));
$mediaFormat = $root->appendChild($dom->createElement('formats'));
foreach ($formats as $k) {
$format = $mediaFormat->appendChild($dom->createElement('format'));
$format->appendChild($dom->createElement('id'))->appendChild($dom->createCDATASection($k['id']));
$format->appendChild($dom->createElement('libelle'))->appendChild($dom->createCDATASection($k['libelle']));
$format->appendChild($dom->createElement('extension'))->appendChild($dom->createCDATASection("$media->extension"));
$format->appendChild($dom->createElement('largeur'))->appendChild($dom->createCDATASection($k['largeur']));
$format->appendChild($dom->createElement('hauteur'))->appendChild($dom->createCDATASection($k['hauteur']));
$format->appendChild($dom->createElement('lien'))->appendChild($dom->createCDATASection(env('APP_URL') . "/$media->folder$media->uid" . "_" . $k['libelle'] . ".$media->extension"));
}
return $dom->saveXML();
}
public static function getRefKey($media)
{
switch ($media->sujet_id) {
case 1:
return $media->articles()->get();
break;
case 2:
return $media->marques()->get();
break;
case 4:
return $media->societes()->get();
break;
default:
return [];
}
}
private static function getFormats()
{
return Format::withoutGlobalScope(SystemScope::class)
->where('system', true)->get();
}
}

View file

@ -1,239 +0,0 @@
<?php
namespace App\Http\Traits;
use App\Models\Format;
use App\Models\Media;
use Illuminate\Support\Facades\Storage;
trait MediaTools
{
public function getFileSize($file_path)
{
return $this->fixIntegerOverflow(filesize($file_path));
}
/**
* Create thumbnail image for a Media
*
* @param Media $media
* @return void
* @throws \ImagickException On errors.
*/
public function createThumb(Media $media)
{
/** @var \Illuminate\Support\Collection<\App\Models\Format> $formats */
$formats = optional($media->sujet)->formats ?? collect();
$mediaPath = public_path("/{$media->folder}{$media->uid}.{$media->extension}");
$im = new \Imagick($mediaPath);
$im->setImageBackgroundColor('#ffffff');
$im->setImageAlphaChannel(\Imagick::ALPHACHANNEL_REMOVE);
$im->mergeImageLayers(\Imagick::LAYERMETHOD_FLATTEN);
$im->stripImage();
if (in_array($media->extension, array("pdf", "ai", "psd"))) {
$im->setIteratorIndex(0);
}
foreach ($formats as $format) {
$fp = public_path("/{$media->folder}{$media->uid}_{$format->libelle}.{$format->extension}");
$targetWidth = \floatval($format->largeur);
if (\floatval($format->hauteur) == 0) {
$targetHeight = \floatval(floor(($media->hauteur * $format->largeur) / $media->largeur));
} else {
$targetHeight = \floatval($format->hauteur);
}
$im->setImageFormat($format->extension);
if ($media->largeur >= $targetWidth || $media->hauteur >= $targetHeight) {
$im->thumbnailImage($targetWidth, $targetHeight, true);
}
$im->writeImage($fp);
}
$im->destroy();
unset($im);
}
/**
* Create Sys thumbnail image for a Media.
*
* @param \App\Models\Media $media
* @return void
* @throws \ImagickException On errors.
*/
public function createSysThumb(Media $media)
{
$mediaPath = public_path("/{$media->folder}{$media->uid}.{$media->extension}");
$im = new \Imagick();
$im->readImage($mediaPath);
if (in_array($media->extension, array("pdf", "ai", "psd"))) {
$extension = "png";
$im->setIteratorIndex(0);
} else {
/** @var string */
$extension = $media->extension;
}
/*
Handle CMJN - DOESN'T WORK
if ($im->getImageColorspace() === \Imagick::COLORSPACE_CMYK){
$im->transformImageColorspace(\Imagick::COLORSPACE_RGB);
}
*/
// * create preview
/** @var \App\Models\Format $format */
$format = Format::withoutGlobalScope('App\Scopes\SystemScope')
->where('libelle', '=', 'preview')->firstOrFail();
$fp = public_path("/{$media->folder}{$media->uid}_preview.{$extension}");
if ($media->extension == "gif") {
if ($media->largeur >= $format->largeur || $media->hauteur >= $format->hauteur || $media->largeur == "") {
$im = $im->coalesceImages();
foreach ($im as $frame) {
$frame->thumbnailImage($format->largeur, $format->hauteur);
$frame->setImagePage($format->largeur, $format->hauteur, 0, 0);
}
$im = $im->deconstructImages();
}
$im->writeImages($fp, true);
} else {
if ($media->largeur >= $format->largeur || $media->hauteur >= $format->hauteur || $media->largeur == "") {
$im->thumbnailImage($format->largeur, $format->hauteur, true);
}
$im->writeImage($fp);
}
// * create thumb
/** @var \App\Models\Format $format */
$format = Format::withoutGlobalScope('App\Scopes\SystemScope')
->where('libelle', '=', 'thumb')->firstOrFail();
if ($extension != "png") {
$im->setImageBackgroundColor('#ffffff');
$im->setImageAlphaChannel(\Imagick::ALPHACHANNEL_REMOVE);
$im->mergeImageLayers(\Imagick::LAYERMETHOD_FLATTEN);
$im->stripImage();
}
$fp = public_path("/{$media->folder}{$media->uid}_thumb.{$extension}");
$im->thumbnailImage($format->largeur, $format->hauteur, true);
$im->writeImage($fp);
$im->destroy();
unset($im);
}
/**
* Returns the media folder path name
*
* @return string
* @throws \ErrorException If creating the folder fails.
*/
public function getMediaFolder(): string
{
$mediaPath = "medias/";
$directories = Storage::allDirectories($mediaPath);
$selectedFolder = "";
// * on obtient le dernier dossier créé
/** @var string $foldername */
foreach ($directories as $key => $foldername) {
if ($selectedFolder < $foldername) {
$selectedFolder = $foldername;
}
}
// * si on n'a pas de dossier, on le créé
if ($selectedFolder == "") {
$selectedFolder = $mediaPath . uniqid();
if (!Storage::makeDirectory($selectedFolder)) {
throw new \ErrorException("Could not create $selectedFolder");
}
} else {
// * on compte le nombre de fichier
$files = Storage::allFiles($selectedFolder);
// * si on en a plus de 1000, on créé un nouveau dossier
if (count($files) > 1000) {
$selectedFolder = $mediaPath . uniqid();
if (!Storage::makeDirectory($selectedFolder)) {
throw new \ErrorException("Could not create $selectedFolder");
}
}
}
return $selectedFolder;
}
public function fixIntegerOverflow($size)
{
if ($size < 0) {
$size += 2.0 * (PHP_INT_MAX + 1);
}
return $size;
}
/**
* Convert file size to human readable string
*
* @param integer $octet
* @param integer $precision
* @return string
*/
public function formatBytes(int $octet, int $precision = 2): string
{
// * Array contenant les differents unités
$unite = array('octet', 'Ko', 'Mo', 'Go');
switch (true) {
// * octet
case $octet < 1000:
return $octet . $unite[0];
// * ko
case $octet < 1000000:
return $octet . $unite[1];
// * Mo ou Go
default:
if ($octet < 1000000000) {
// * Mo
$mo = round($octet / (1024 * 1024), $precision);
return $mo . $unite[2];
} else {
// * Go
$go = round($octet / (1024 * 1024 * 1024), $precision);
return $go . $unite[3];
}
}
}
/**
* Renvoi le chemin attendu d'un média selon le format demandé
*
* @param \App\Models\Media $media
* @param \App\Models\Format $format
* @return string
* @throws \ErrorException If Format is not handled.
*/
public function getMediaPath(Media $media, Format $format): string
{
// * format spécifique
if ($format->system) {
if (in_array($media->extension, array("gif", "jpeg", "jpg", "png", "pdf", "ai", "psd"))) {
return public_path("/{$media->folder}{$media->uid}_{$format->libelle}.{$format->extension}");
}
return public_path("/{$media->folder}{$media->uid}.{$media->extension}");
}
// * format système (thumb et preview)
if ($format->system) {
if (in_array($media->extension, array("gif", "jpeg", "jpg", "png"))) {
// * Gestion du cas de format qui fixe l'extension
if ($format->extension != '') {
$file_extension = $format->extension;
} else {
$file_extension = $media->extension;
}
return public_path("/{$media->folder}{$media->uid}_{$format->libelle}.{$file_extension}");
} elseif (in_array($media->extension, array("pdf", "ai", "psd"))) {
return public_path("/{$media->folder}{$media->uid}_{$format->libelle}.png");
}
return public_path("/{$media->folder}.{$media->uid}.{$media->extension}");
}
throw new \ErrorException("Unhandled Format $format->id $format->libelle");
}
}

View file

@ -3,7 +3,6 @@
namespace App\Jobs\Arcadia;
use App\Exceptions\AbortXmlImportException;
use App\Exceptions\ElasticSearchException;
use App\Models\ArcadiaLink;
use App\Models\Media;
use Illuminate\Database\Eloquent\ModelNotFoundException;
@ -62,7 +61,7 @@ class XmlArcadiaMediasIn extends XmlJobs
$this->parseData('MEDIA_VISUEL', Media::class, function (\SimpleXMLElement $xmlData, array &$line) {
// * After XML parse Callback.
// * Unlock media
$line['isLocked'] = 0;
$line['isLocked'] = false;
}, function (array $uniqueColumnsKey, $line) {
// * DO the DB save yourself callback
try {
@ -71,16 +70,13 @@ class XmlArcadiaMediasIn extends XmlJobs
$media->arcadia_id = $line['arcadia_id'];
$media->version = $line['version'];
$media->isLocked = 0;
$media->isLocked = false;
$media->saveOrFail();
} catch (ModelNotFoundException $e) {
$e = new AbortXmlImportException(
sprintf('La fiche media \'%s\' ne peut être trouvé', \json_encode($uniqueColumnsKey)),
0,
1,
__FILE__,
__LINE__,
$e
);
throw $e;
@ -96,11 +92,8 @@ class XmlArcadiaMediasIn extends XmlJobs
$media = Media::withTrashed()->findOrFail($line['id']);
} catch (ModelNotFoundException $e) {
$e = new AbortXmlImportException(
"La fiche media '%s' ne peut être trouvé",
\sprintf('La fiche media \'%s\' ne peut être trouvé', $line['id']),
0,
1,
__FILE__,
__LINE__,
$e
);
throw $e;
@ -108,36 +101,16 @@ class XmlArcadiaMediasIn extends XmlJobs
try {
// * Suppression dans la supervision Arcadia Link
/** @var \App\Models\ArcadiaLink|null */
$arcadiaLink = ArcadiaLink::where('media_id', $media->id)->first();
if ($arcadiaLink) {
$arcadiaLink->delete();
$arcadiaLink->deleteOrFail();
}
// * Index ElasticSearch
$esExist = Media::searchByQuery([
'match' => ['arcadia_id' => $media->arcadia_id ?? '']
]);
// * Remove all from elastic if any duplicates
if ($esExist->totalHits() > 0) {
$media->removeFromIndex();
}
if (!$media->trashed()) {
// * Save into elastic
$media->addToIndex();
}
} catch (\Exception $e) {
$report = new ElasticSearchException(
'Something went wrong when updating media into elastic search',
0,
1,
__FILE__,
__LINE__,
$e
);
report($report);
throw new AbortXmlImportException($report->getMessage());
// * Save into elastic if media is not soft deleted, remove otherwise.
!$media->trashed() ? $media->addToElasticSearch() : $media->removeFromElasticSearch();
} catch (\RuntimeException $e) {
throw new AbortXmlImportException($e->getMessage());
} //end try
});
}

View file

@ -21,15 +21,6 @@ class SendMediasModificationsReport implements ShouldQueue
use Queueable;
use SerializesModels;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct()
{
}
/**
* Execute the job.
*
@ -37,28 +28,31 @@ class SendMediasModificationsReport implements ShouldQueue
*/
public function handle()
{
// Gather Medias to report
// filtered by subject (2,4)
$now = Carbon::now();
$yesterday = $now->subDay(1);
$arSujets = [];
$onesujet = Sujet::find(2);
array_push($arSujets, $onesujet->libelle);
$onesujet = Sujet::find(4);
array_push($arSujets, $onesujet->libelle);
// Gather Medias to report.
$subjectsToFetch = [
// * Marques
2,
// * Sociétés
4,
];
$sujets = implode(', ', $arSujets);
$yesterday = Carbon::now()->subDay(1);
$medias = Media::whereDate('updated_at', '>=', $yesterday)
/** @var \Illuminate\Database\Eloquent\Collection<\App\Models\Sujet> */
$sujets = Sujet::whereIn('codeSujet', $subjectsToFetch)->get();
/** @var \Illuminate\Database\Eloquent\Collection<\App\Models\Media> */
$mediaList = Media::whereDate('updated_at', '>=', $yesterday)
->whereIn('sujet_id', [2,4])
->get();
// send mail
/** @var \App\Models\Setting|null Send mail */
$toMailSetting = Setting::where('key', 'media_report_to_mail')->first();
if (empty($toMailSetting->value)) {
// pas d'envoi car pas de mail cible
} else {
$email = $toMailSetting->value;
Mail::to($email)->send(new SendMediaReportMail($medias, $yesterday, $sujets));
if ($toMailSetting and !empty(\strval(optional($toMailSetting)->value))) {
Mail::to(\strval($toMailSetting->value))->send(new SendMediaReportMail(
$mediaList,
$yesterday,
$sujets->pluck('libelle')->implode(', ')
));
}
}
}

View file

@ -0,0 +1,294 @@
<?php
namespace App\Lib;
use App\Enums\EdiMouvementType;
use App\Models\ArcadiaLink;
use App\Models\Format;
use App\Models\Media;
use App\Scopes\SystemScope;
use DOMDocument;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
class ArcadiaLinkUtilities
{
/**
* Create Media
*
* @param \App\Models\Media $media
* @return boolean
*/
public static function create(Media $media): bool
{
return self::sendMediaToArcadia($media, EdiMouvementType::create);
}
/**
* Update Media
*
* @param \App\Models\Media $media
* @return boolean
*/
public static function update(Media $media): bool
{
return self::sendMediaToArcadia($media, EdiMouvementType::update);
}
/**
* Delete Media
*
* @param \App\Models\Media $media
* @return boolean
*/
public static function delete(Media $media): bool
{
return self::sendMediaToArcadia($media, EdiMouvementType::delete);
}
/**
* Reactivate Media
*
* @param \App\Models\Media $media
* @return boolean
*/
public static function reactivate(Media $media): bool
{
return self::sendMediaToArcadia($media, EdiMouvementType::reactivate);
}
/**
* Send Media mouvement to Arcadia
*
* @param \App\Models\Media $media
* @param \App\Enums\EdiMouvementType $ediMouvementType
* @return boolean
*/
private static function sendMediaToArcadia(Media $media, EdiMouvementType $ediMouvementType): bool
{
if (
$ediMouvementType !== EdiMouvementType::create and
$media->arcadia_id === null and
!self::hasRequiredValues($media)
) {
return false;
}
$media->fresh();
$media->isLocked = true;
try {
if (
!($media->saveQuietly() and
self::compress(self::generateXml($media, $ediMouvementType), $media)
)
) {
return false;
}
/** @throws \RuntimeException */
$media->addToElasticSearch();
return true;
} catch (\RuntimeException | \Throwable $e) {
report($e);
return false;
}
}
/**
* Check has required values
*
* @param \App\Models\Media $media
* @return boolean
*/
private static function hasRequiredValues(Media $media): bool
{
$required = ['sujet_id', 'type_media_id', 'type_vue_id', 'variante_id', 'langue_id', 'version'];
foreach ($required as $v) {
if ($media->{$v} === null) {
return false;
}
}
return true;
}
/**
* Compress Xml File into zip
*
* @param string $xml
* @param \App\Models\Media $media
* @return boolean
*/
private static function compress(string $xml, Media $media): bool
{
/** @var \Illuminate\Filesystem\FilesystemAdapter */
$storage = Storage::disk('arcadia_link_s');
$uuid = Str::uuid();
$filename = "{$media->id}-{$uuid}.zip";
$zip = new \ZipArchive();
$success = $zip->open(
$storage->path($filename),
\ZipArchive::CREATE | \ZipArchive::OVERWRITE
);
$success = $zip->addFromString($xml, 'media.xml') && $success;
$success = $zip->addFile($media->full_path, $media->basename) && $success;
$success = $zip->close() && $success;
unset($zip);
// On insert dans la table de supervision.
$arcadiaLink = new ArcadiaLink();
$arcadiaLink->media_id = $media->id;
if ($media->arcadia_id !== null) {
$arcadiaLink->arcadia_id = $media->arcadia_id;
}
$arcadiaLink->filename = $filename;
return $success and $arcadiaLink->save();
}
/**
* Generate Xml
*
* @param \App\Models\Media $media
* @param \App\Enums\EdiMouvementType $mouvement
* @return string
* @throws \RuntimeException If Generating XML Fails.
*/
private static function generateXml(Media $media, EdiMouvementType $mouvement): string
{
$refKey = self::getRefKey($media);
$formats = self::getFormats();
$dom = new DOMDocument('1.0', 'UTF-8');
$dom->formatOutput = true;
try {
$root = $dom->createElement('MEDIA_VISUEL');
$dom->appendChild($root);
$root->appendChild($dom->createElement('codeArcadia'))
->appendChild($dom->createCDATASection("$media->arcadia_id"));
$root->appendChild($dom->createElement('code_DAM'))
->appendChild($dom->createCDATASection("$media->id"));
$root->appendChild($dom->createElement('TypeMouvement'))
->appendChild($dom->createCDATASection("$mouvement->value"));
$cleRef = $root->appendChild($dom->createElement('cle_Referentiel'));
foreach ($refKey as $model) {
if ($media->sujet_id === 1) {
$cleRef->appendChild($dom->createElement('id'))
->appendChild($dom->createCDATASection("$model->noArt"));
} elseif ($media->sujet_id === 2) {
$cleRef->appendChild($dom->createElement('id'))
->appendChild($dom->createCDATASection("$model->codMarq"));
} elseif ($media->sujet_id === 4) {
$cleRef->appendChild($dom->createElement('id'))
->appendChild($dom->createCDATASection("$model->id"));
}
}
$root->appendChild($dom->createElement('libExtension'))
->appendChild($dom->createCDATASection($media->extension->value));
$root->appendChild($dom->createElement('nbPxLargeur'))
->appendChild($dom->createCDATASection("$media->largeur"));
$root->appendChild($dom->createElement('largeurMm'))
->appendChild($dom->createCDATASection("$media->largeur_mm"));
$root->appendChild($dom->createElement('nbPxHauteur'))
->appendChild($dom->createCDATASection("$media->hauteur"));
$root->appendChild($dom->createElement('hauteurMm'))
->appendChild($dom->createCDATASection("$media->hauteur_mm"));
$root->appendChild($dom->createElement('pppLargeur'))
->appendChild($dom->createCDATASection("$media->resolution"));
$root->appendChild($dom->createElement('version'))
->appendChild($dom->createCDATASection("$media->version"));
$root->appendChild($dom->createElement('codeTypeMedia'))
->appendChild($dom->createCDATASection("$media->type_media_id"));
$root->appendChild($dom->createElement('codeTypeVue'))
->appendChild($dom->createCDATASection("$media->type_vue_id"));
$root->appendChild($dom->createElement('commentaire'))
->appendChild($dom->createCDATASection("$media->commentaire"));
$root->appendChild($dom->createElement('codeSujet'))
->appendChild($dom->createCDATASection("$media->sujet_id"));
$root->appendChild($dom->createElement('langue'))
->appendChild($dom->createCDATASection("$media->langue_id"));
$root->appendChild($dom->createElement('copyright'))
->appendChild($dom->createCDATASection("$media->copyright_id"));
$root->appendChild($dom->createElement('codeVariante'))
->appendChild($dom->createCDATASection("$media->variante_id"));
$root->appendChild($dom->createElement('dateCreation'))
->appendChild($dom->createCDATASection("$media->created_at"));
$root->appendChild($dom->createElement('dateModification'))
->appendChild($dom->createCDATASection("$media->updated_at"));
$root->appendChild($dom->createElement('datePublication'))
->appendChild($dom->createCDATASection("$media->published_at"));
$root->appendChild($dom->createElement('libelle'))
->appendChild($dom->createCDATASection("$media->libelle"));
$root->appendChild($dom->createElement('NomFichier'))
->appendChild($dom->createCDATASection("$media->uid.{$media->extension->value}"));
$mediaFormat = $root->appendChild($dom->createElement('formats'));
foreach ($formats as $formatModel) {
$format = $mediaFormat
->appendChild($dom->createElement('format'));
$format->appendChild($dom->createElement('id'))
->appendChild($dom->createCDATASection($formatModel['id']));
$format->appendChild($dom->createElement('libelle'))
->appendChild($dom->createCDATASection($formatModel['libelle']));
$format->appendChild($dom->createElement('extension'))
->appendChild($dom->createCDATASection($media->extension->value));
$format->appendChild($dom->createElement('largeur'))
->appendChild($dom->createCDATASection($formatModel['largeur']));
$format->appendChild($dom->createElement('hauteur'))
->appendChild($dom->createCDATASection($formatModel['hauteur']));
$format->appendChild($dom->createElement('lien'))
->appendChild($dom->createCDATASection(\sprintf(
"%s/{$media->folder}{$media->uid}_%s.{$media->extension->value}",
config('app.url'),
$formatModel['libelle']
)));
}
} catch (\DOMException | \Exception $e) {
report($e);
throw new \RuntimeException('Failed to generate XML', 0, $e);
} //end try
if (!($xml = $dom->saveXML())) {
throw new \RuntimeException('Failed to generate XML');
}
return $xml;
}
/**
* Get Ref Key
*
* @param \App\Models\Media $media
* @return \Illuminate\Support\Collection<\App\Models\Article|\App\Models\Marque|\App\Models\Societe>
*/
public static function getRefKey(Media $media): Collection
{
switch ($media->sujet_id) {
case 1:
return $media->articles;
case 2:
return $media->marques;
case 4:
return $media->societes;
default:
return collect();
}
}
/**
* Get Formats
*
* @return \Illuminate\Support\Collection<\App\Models\Format>
*/
private static function getFormats(): Collection
{
return Format::withoutGlobalScope(SystemScope::class)
->where('system', true)->get();
}
}

255
app/Lib/ToolboxHelper.php Normal file
View file

@ -0,0 +1,255 @@
<?php
namespace App\Lib;
use App\Enums\MediaExtension;
use getID3;
use Illuminate\Support\Str;
use Imagick;
use ImagickException;
class ToolboxHelper
{
/**
* Get ID3 Play time string
*
* @param string $filepath
* @return string|null
*/
public static function getId3Playtime(string $filepath): ?string
{
$getID3 = new getID3();
$results = $getID3->analyze($filepath);
if (array_key_exists('error', $results)) {
return null;
}
if (array_key_exists('playtime_string', $results)) {
return \strval($results['playtime_string']);
}
return null;
}
/**
* Get ID3 video dimensions
*
* @param string $filepath
* @return array|null Containing 'width' and 'height'
*/
public static function getId3VideoDimensions(string $filepath): ?array
{
$getID3 = new getID3();
$results = $getID3->analyze($filepath);
if (array_key_exists('error', $results)) {
return null;
}
if (isset($results['video']['resolution_x']) and isset($results['video']['resolution_y'])) {
return [
'width' => \intval($results['video']['resolution_x']),
'height' => \intval($results['video']['resolution_y'])
];
}
return null;
}
/**
* resolution in pixels per centimeter
*
* @param string $filepath
* @return array|null Containing 'resolutionX', 'resolutionY', 'width' and 'height'
*/
public static function getImageDimensions(string $filepath): ?array
{
$ext = \pathinfo($filepath, \PATHINFO_EXTENSION);
try {
$im = new Imagick($filepath);
if (
in_array($ext, [
MediaExtension::pdf->value,
MediaExtension::ai->value,
MediaExtension::psd->value,
MediaExtension::gif->value
])
) {
$im->setIteratorIndex(0);
}
$r = $im->getImageResolution();
$u = $im->getImageUnits();
// Force image resolution to pixel per centimeters.
if ($u == Imagick::RESOLUTION_PIXELSPERINCH) {
$r['x'] = (int)round($r['x'] / 2.54);
$r['y'] = (int)round($r['y'] / 2.54);
$im->setImageUnits(Imagick::RESOLUTION_PIXELSPERCENTIMETER);
$im->setImageResolution($r['x'], $r['y']);
// Note that the number type is double again.
$r = $im->getImageResolution();
}
$imageprops = $im->getImageGeometry();
$im->destroy();
return [
'resolutionX' => \intval($r['x']),
'resolutionY' => \intval($r['y']),
'width' => \intval($imageprops['width']),
'height' => \intval($imageprops['height'])
];
} catch (ImagickException $e) {
report($e);
} //end try
return null;
}
/**
* Sanitize File name for uploaded files
*
* @param string $filename The original uploaded client file name.
* @param boolean $beautify Beautify the filename.
* @return string The sanitized file name.
*/
public static function sanitizeFileName(string $filename, bool $beautify = true): string
{
// * Sanitize filename
// phpcs:disable Generic.Files.LineLength.TooLong
$filename = preg_replace(
'~
[<>:"/\\\|?*]| # file system reserved https://en.wikipedia.org/wiki/Filename#Reserved_characters_and_words
[\x00-\x1F]| # control characters http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247%28v=vs.85%29.aspx
[\x7F\xA0\xAD]| # non-printing characters DEL, NO-BREAK SPACE, SOFT HYPHEN
[#\[\]@!$&\'()+,;=]| # URI reserved https://tools.ietf.org/html/rfc3986#section-2.2
[{}^\~`] # URL unsafe characters https://www.ietf.org/rfc/rfc1738.txt
~x',
'-',
$filename
);
// phpcs:enable
// * Avoids '.' '..' or '.hiddenFiles' .
$filename = Str::of($filename)->ltrim('.-');
// * Optional beautification
if ($beautify) {
$filename = static::beautifyFilename($filename);
}
// * Maximize filename length to 255 bytes http://serverfault.com/a/9548/44086
/** @var string */
$extension = pathinfo($filename, \PATHINFO_EXTENSION);
/** @var string */
$filename = pathinfo($filename, \PATHINFO_FILENAME);
$encoding = mb_detect_encoding($filename);
$encoding = $encoding ? $encoding : null;
return \mb_strcut(
$filename,
0,
255 - (!empty($extension) ? strlen($extension) + 1 : 0),
$encoding
) . (!empty($extension) ? ".$extension" : '');
}
/**
* Beautify a filename
*
* @param string $filename
* @return string
*/
private static function beautifyFilename(string $filename): string
{
// Reduce consecutive characters.
$filename = preg_replace([
// * "file name.zip" becomes 'file-name.zip'
'/ +/',
// * "file___name.zip" becomes 'file-name.zip'
'/_+/',
// * "file---name.zip" becomes 'file-name.zip'
'/-+/'
], '-', $filename);
$filename = preg_replace([
// * "file--.--.-.--name.zip" becomes "file.name.zip"
'/-*\.-*/',
// * "file...name..zip" becomes "file.name.zip"
'/\.{2,}/'
], '.', $filename);
// Lowercase for windows/unix interoperability http://support.microsoft.com/kb/100625 .
$filename = mb_strtolower($filename, mb_detect_encoding($filename));
// * ".file-name.-" becomes "file-name"
$filename = trim($filename, '.-');
return $filename;
}
/**
* Convert file size to human readable string
*
* @param mixed $octet
* @param integer $precision
* @return string
*/
public static function formatBytes(mixed $octet, int $precision = 2): string
{
// * Array contenant les differents unités
$unite = ['octet', 'Kio', 'Mio', 'Gio'];
$octet = \floatval($octet);
$Kio = 1024;
$Mio = 1024 * $Kio;
$Gio = 1024 * $Mio;
switch (true) {
// * octet
case $octet < $Kio:
return $octet . $unite[0];
// * kio
case $octet < $Mio:
return $octet . $unite[1];
// * Mio
case $octet < $Gio:
return \round($octet / $Mio, $precision) . $unite[2];
// * Gio
default:
// * Gio
return \round($octet / $Gio, $precision) . $unite[3];
}
}
/**
* * Register CSP report URI
*
* Put this function inside RouteServiceProvider,
* and call it in RouteServiceProvider::boot
*
* ! Use this in conjonction with kwaadpepper/exception-handler
*
* @return void
*/
public static function cspReportRoute()
{
// * CSP REPORT URI, Please add /csp-report to VerifyCsrfToken $except middleware
\Illuminate\Support\Facades\Route::post('/csp-report', function () {
$isCspRequest = request()->header('Content-Type') === 'application/csp-report';
if (!$isCspRequest or !request()->json('csp-report') or !is_array(request()->json('csp-report'))) {
abort(401);
}
// * Flatten if needed
$cspReport = collect(request()->json('csp-report'))
->flatMap(function ($v, $k) {
return [$k => is_array($v) ? collect($v)->flatten()->implode(', ') : $v];
})->all();
// * Filter array keys
$cspReport = collect(array_intersect_key($cspReport, [
'blocked-uri' => '', 'document-uri' => '', 'original-policy' => '',
'referrer' => '', 'violated-directive' => ''
]));
report(new \Illuminate\Http\Client\HttpClientException(sprintf(
"CSP REPORT for %s : \n %s",
$cspReport->get('document-uri'),
$cspReport->implode("\n")
)));
})->middleware('throttle:5,2')
->withoutMiddleware(\App\Http\Middleware\VerifyCsrfToken::class)
->name('cspReportUri');
}
}

View file

@ -0,0 +1,26 @@
<?php
namespace App\Listeners;
use App\Events\MediaSearched;
use App\Models\Recherche;
class CleanUserOldSearches
{
/**
* Handle the event.
*
* @param \App\Events\MediaSearched $event
* @return void
* @throws \RuntimeException If linking with Arcadia failed.
*/
public function handle(MediaSearched $event)
{
// * Purge des anciennes recherches
$count = Recherche::where('user_id', $event->getUser()->id)->count();
Recherche::where('user_id', $event->getUser()->id)->orderBy("updated_at", "desc")
->skip(10)->take($count)->get()->each(function (Recherche $recherche) {
$recherche->deleteOrFail();
});
}
}

View file

@ -0,0 +1,35 @@
<?php
namespace App\Listeners;
use App\Events\MediaLinkWithArcadia;
use App\Lib\ArcadiaLinkUtilities;
use App\Models\Historique;
class CreateIntoArcadia
{
/**
* Handle the event.
*
* @param \App\Events\MediaLinkWithArcadia $event
* @return void
* @throws \RuntimeException If linking with Arcadia failed.
*/
public function handle(MediaLinkWithArcadia $event)
{
$user = $event->getUser();
$media = $event->getMedia();
$historique = new Historique();
$historique->type = trans('Modification');
$historique->description = trans('Ajout de la liaison Arcadia');
$historique->media()->associate($media);
$historique->user()->associate($user);
// * Link To arcadia
if (!ArcadiaLinkUtilities::create($media)) {
throw new \RuntimeException('Failed to link media with Arcadia');
}
$historique->saveOrFail();
}
}

View file

@ -0,0 +1,76 @@
<?php
namespace App\Listeners;
use App\Events\MediaChangedLabel;
use App\Events\MediaCreated;
use App\Events\MediaDestroyed;
use App\Events\MediaMoved;
use App\Events\MediaUpdated;
use App\Models\Historique;
class HistorizeMediaEvent
{
/**
* Handle the event.
*
* @param \App\Events\MediaCreated $event
* @return void
* @throws \RuntimeException If saving historic to database failed.
*/
public function handle(MediaCreated $event)
{
$historique = new Historique();
// TODO: put enum in here.
$type = trans('Création');
$description = trans('Média ajouté');
if ($event instanceof MediaMoved) {
$type = trans('Déplacement');
$description = $event->getMedia()->dossier_id > 0 ?
trans('Déplacement dans le dossier :libelle', [
'libelle' => $event->getMedia()->dossier->libelle
]) : trans('Média déplacé à la racine');
}
if ($event instanceof MediaUpdated) {
$type = trans('Modification');
$description = trans('Le média a été mis à jour');
}
if ($event instanceof MediaDestroyed) {
$type = trans('Suppression');
$description = trans('Le média a été supprimé');
}
if ($event instanceof MediaChangedLabel) {
$type = trans('Etiquette');
$description = sprintf(
'%s -> %s',
\optional($event->getOldLabel())->libelle ?? trans('aucune'),
\optional($event->getNewLabel())->libelle ?? trans('aucune')
);
}
$historique->user()->associate($event->getUser());
$historique->media()->associate($event->getMedia());
$historique->type = $type;
$historique->description = $description;
if (!$historique->save()) {
throw new \RuntimeException('Failed to save historic to Database');
}
}
/**
* Handle a job failure.
*
* @param mixed $event
* @param \Throwable $exception
* @return void
* @phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter.FoundBeforeLastUsed
*/
public function failed(mixed $event, \Throwable $exception)
{
//phpcs:enable
report($exception);
}
}

View file

@ -0,0 +1,28 @@
<?php
namespace App\Listeners;
use App\Events\MediaSearched;
use App\Models\Recherche;
class SaveUserSearch
{
/**
* Handle the event.
*
* @param \App\Events\MediaSearched $event
* @return void
* @throws \RuntimeException If linking with Arcadia failed.
*/
public function handle(MediaSearched $event)
{
$recherche = Recherche::where('libelle', $event->getSearchString())->firstOrNew();
$recherche->dossier_id = $event->getDossierId();
$recherche->filters = $event->getFilters();
$recherche->libelle = $event->getSearchString();
$recherche->sujet()->associate($event->getSujet());
$recherche->user()->associate($event->getUser());
$recherche->saveOrFail();
}
}

View file

@ -0,0 +1,56 @@
<?php
namespace App\Listeners;
use App\Events\MediaCreated;
use App\Events\MediaDestroyed;
use App\Events\MediaUpdated;
use App\Lib\ArcadiaLinkUtilities;
class SyncWithArcadia
{
/**
* Handle the event.
*
* @param \App\Events\MediaCreated $event
* @return void
* @throws \RuntimeException If linking with Arcadia failed.
* @throws \ErrorException If event ins unhandled.
*/
public function handle(MediaCreated $event)
{
$media = $event->getMedia();
$succeed = false;
if ($event instanceof MediaUpdated or $event instanceof MediaDestroyed) {
// ? Is it locked ?
if ($media->isLocked) {
throw new \RuntimeException('Tried to sync a locked Media');
}
}
switch (true) {
case $event instanceof MediaUpdated:
// ! Le média n'est pas un brouillon.
if ($event->getMedia()->statut !== 0) {
$succeed = ArcadiaLinkUtilities::update($event->getMedia());
} else {
$succeed = true;
}
break;
case $event instanceof MediaDestroyed:
$succeed = ArcadiaLinkUtilities::delete($event->getMedia());
break;
case $event instanceof MediaCreated:
$succeed = ArcadiaLinkUtilities::create($event->getMedia());
break;
default:
throw new \ErrorException('Unhandled event ' . \get_class($event));
}
if (!$succeed) {
throw new \RuntimeException('Failed to sync media with Arcadia');
}
}
}

View file

@ -1,47 +0,0 @@
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class Contact extends Mailable
{
use Queueable;
use SerializesModels;
public $type;
public $url;
public $message;
public $user;
/**
* Create a new message instance.
*
* @return void
*/
public function __construct($type, $url, $message, $user)
{
$this->type = $type;
$this->url = $url;
$this->message = $message;
$this->user = $user;
}
/**
* Build the message.
*
* @return $this
*/
public function build()
{
return $this->from('dam@ldc.fr', 'DAM')
->subject('Message d\'un utilisateur')
->view('mails.contact')
->with(['type' => $this->type, 'url' => $this->url, 'messagetxt' => $this->message, 'user' => $this->user]);
}
}

55
app/Mail/ContactMail.php Normal file
View file

@ -0,0 +1,55 @@
<?php
namespace App\Mail;
use App\Enums\ContactType;
use App\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class ContactMail extends Mailable
{
use Queueable;
use SerializesModels;
/** @var \App\Enums\ContactType */
public $type;
/** @var string */
public $url;
/** @var string */
public $messagetxt;
/** @var \App\Models\User */
public $user;
/**
* Create a new message instance.
*
* @param \App\Enums\ContactType $type
* @param string $url
* @param string $message
* @param \App\Models\User $user
*/
public function __construct(ContactType $type, string $url, string $message, User $user)
{
$this->type = $type;
$this->url = $url;
$this->messagetxt = $message;
$this->user = $user;
}
/**
* Build the message.
*
* @return $this
*/
public function build()
{
return $this->from('dam@ldc.fr', 'DAM')
->subject('Message d\'un utilisateur')
->view('mails.contact');
}
}

View file

@ -2,24 +2,36 @@
namespace App\Mail;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Carbon;
class SendMediaReportMail extends Mailable
{
use Queueable;
use SerializesModels;
/** @var \Illuminate\Database\Eloquent\Collection<\App\Models\Media> */
private $mediaList;
/** @var \Illuminate\Support\Carbon */
private $yesterday;
/** @var string */
private $sujet;
/**
* Create a new message instance.
*
* @return void
* @param \Illuminate\Database\Eloquent\Collection $mediaList
* @param \Illuminate\Support\Carbon $yesterday
* @param string $sujets
*/
public function __construct($medias, $yesterday, $sujets)
public function __construct(Collection $mediaList, Carbon $yesterday, string $sujets)
{
$this->medias = $medias;
$this->mediaList = $mediaList;
$this->yesterday = $yesterday;
$this->sujets = $sujets;
}
@ -32,10 +44,12 @@ class SendMediaReportMail extends Mailable
public function build()
{
$now = Carbon::now();
$medias = $this->medias;
$mediaList = $this->mediaList;
$yesterday = $this->yesterday;
$sujets = $this->sujets;
return $this->subject("Rapport d'activité DAM - " . $now->formatLocalized('%d %B %Y à %H:%M'))->view('mails.send-media-report', compact('medias', 'yesterday', 'sujets'));
return $this->subject(
"Rapport d'activité DAM - " . $now->isoFormat('DD/MM/YYYY à HH:mm')
)->view('mails.send-media-report', compact('mediaList', 'yesterday', 'sujets'));
}
}

View file

@ -7,13 +7,6 @@ use Carbon\Carbon;
class ArcadiaLink extends Model
{
/**
* *The table associated with the model.
*
* @var string
*/
protected $table = 'arcadia_link';
// * GETTERS
/**

View file

@ -6,11 +6,17 @@ use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
// * RELATIONSHIPS
/**
* The medias that belong to the article.
* BelongsToMany mediaList relation
*
* The mediaList that belong to the article.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function medias()
public function mediaList()
{
return $this->belongsToMany('App\Models\Media', 'medias_articles', 'article_id', 'media_id');
return $this->belongsToMany(Media::class);
}
}

View file

@ -12,4 +12,18 @@ class Copyright extends Model
* @var string
*/
protected $primaryKey = 'copyright_id';
// * METHODS
/**
* Get brandcopyright
*
* @return self
* @throws \RuntimeException If fetching brand copyright fails.
*/
public static function getBrandCopyright(): self
{
return self::whereCopyrightId(3)->first() ??
throw new \RuntimeException('Failed to fetch brand copyright');
}
}

View file

@ -26,6 +26,25 @@ class Dossier extends Model
'favoris', 'mediacount'
];
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
'is_private' => 'bool'
];
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'libelle', 'description',
'is_private', 'parent_id'
];
// * GETTERS
/**
@ -56,15 +75,15 @@ class Dossier extends Model
// * dossier classic
if ($this->parent_id != 1 && $this->id != 1) {
if ($user->hasRole(config('roles.const.ADMIN'))) {
return $this->medias()->count();
return $this->mediaList()->count();
} else {
return $this->medias()
return $this->mediaList()
->where('statut', '<>', config('services.statut.brouillon'))
->orWhere('created_by', $user->id)->count();
}
} else {
// * dossier dépôt
return $this->medias()->count();
return $this->mediaList()->count();
}
}
@ -78,7 +97,7 @@ class Dossier extends Model
*/
public function marques()
{
return $this->belongsToMany(Marque::class, 'marques_dossiers', 'dossier_id', 'marque_id');
return $this->belongsToMany(Marque::class, 'marque_dossier', 'dossier_id', 'marque_id');
}
/**
@ -94,11 +113,11 @@ class Dossier extends Model
/**
* HasMany media relation
* Get the dossier for the sujet.
* Get the dossier for the media.
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function medias()
public function mediaList()
{
return $this->hasMany(Media::class, 'dossier_id', 'id');
}
@ -133,7 +152,7 @@ class Dossier extends Model
*/
public function users()
{
return $this->belongsToMany(User::class, 'dossiers_users', 'dossier_id', 'user_id');
return $this->belongsToMany(User::class);
}
// * METHODS

View file

@ -13,11 +13,29 @@ class Etiquette extends Model
*/
protected $primaryKey = 'etiquette_id';
// * RELATIONSHIPS
/**
* Get the medias for the etiquette.
* HasMany media relation
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function medias()
public function mediaList()
{
return $this->hasMany('App\Models\Media');
return $this->hasMany(Media::class);
}
// * METHODS
/**
* Get no label
*
* @return self
* @throws \RuntimeException If fetching default label no label fails.
*/
public static function getDefaultEtiquette(): self
{
return self::whereEtiquetteId(0)->first() ??
throw new \RuntimeException('Failed to fetch label no label');
}
}

View file

@ -17,11 +17,17 @@ class Format extends Model
'system' => 'bool',
];
// * RELATIONSHIPS
/**
* BelongsToMany sujets relation
*
* The sujet that belong to the format.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function sujets()
{
return $this->belongsToMany('App\Models\Sujet', 'sujets_formats', 'format_id', 'sujet_id');
return $this->belongsToMany(Sujet::class);
}
}

View file

@ -1,9 +0,0 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class FormatRestriction extends Model
{
}

View file

@ -6,21 +6,36 @@ use Illuminate\Database\Eloquent\Model;
class Historique extends Model
{
/**
* Indicates if the model should be timestamped.
*
* @var boolean
*/
public $timestamps = false;
// * RELATIONSHIPS
/**
* BelongsTo user relation
*
* Get the user that owns the historique.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function user()
{
return $this->belongsTo('App\Models\User', 'user_id');
return $this->belongsTo(User::class);
}
/**
* BelongsTo media relation
*
* Get the media that owns the historique.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function media()
{
return $this->belongsTo('App\Models\Media', 'media_id');
return $this->belongsTo(Media::class);
}
}

View file

@ -12,4 +12,18 @@ class Langue extends Model
* @var string
*/
protected $primaryKey = 'langue_id';
// * METHODS
/**
* Get default language instance
*
* @return self
* @throws \RuntimeException If fetching default language fails.
*/
public static function getDefaultLang(): self
{
return self::whereLangueId(1)->first() ??
throw new \RuntimeException('Failed to fetch default language');
}
}

View file

@ -14,26 +14,47 @@ class Marque extends Model
protected $primaryKey = 'codMarq';
/**
* Indicates if the IDs are auto-incrementing.
*
* @var boolean
*/
public $incrementing = false;
// * RELATIONSHIPS
/**
* BelongsToMany users relation
*
* The users that belong to the marque.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function users()
{
return $this->belongsToMany('App\Models\User', 'marques_users', 'marque_id', 'user_id');
return $this->belongsToMany(User::class);
}
/**
* The dossier that belong to the marque.
*/
/**
* BelongsToMany dossiers relation
*
* The dossier that belong to the marque.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function dossiers()
{
return $this->belongsToMany('App\Models\Dossier', 'marques_dossier', 'marque_id', 'dossier_id');
return $this->belongsToMany(Dossier::class, 'marques_dossier', 'marque_id', 'dossier_id');
}
/**
* The medias that belong to the marques.
*/
public function medias()
/**
* BelongsToMany relation
*
* The media that belong to the marques.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function mediaList()
{
return $this->belongsToMany('App\Models\Media', 'medias_marques', 'marque_id', 'media_id');
return $this->belongsToMany(Media::class);
}
}

View file

@ -2,25 +2,26 @@
namespace App\Models;
use App\Http\Traits\ElasticTrait;
use App\Enums\MediaExtension;
use App\Events\MediaChangedLabel;
use App\Events\MediaCreated;
use App\Events\MediaDestroyed;
use App\Events\MediaUpdated;
use App\Lib\ToolboxHelper;
use App\Traits\Models\BindedToElasticSearch;
use App\Models\User;
use Elasticquent\ElasticquentTrait;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Prunable;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\ValidationException;
class Media extends Model
{
use ElasticquentTrait;
use ElasticTrait;
use BindedToElasticSearch;
use Prunable;
use SoftDeletes;
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'medias';
/**
* The relations to eager load on every query.
*
@ -28,7 +29,7 @@ class Media extends Model
*/
protected $with = [
'owner', 'tags', 'etiquette', 'articles', 'sujet',
'typemedia', 'societes', 'marques'
'typeMedia', 'societes', 'marques'
];
/**
@ -38,7 +39,27 @@ class Media extends Model
*/
protected $fillable = [
// ! id est obligatoire ici pour Jobs/XmlArcadiaMediasIn
'id'
'id',
'libelle',
'type_vue_id',
'variante_id',
'copyright_id',
'etiquette_id',
'langue_id',
'commentaire',
'version',
'statut',
];
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
'isDefault' => 'bool',
'isLocked' => 'bool',
'extension' => MediaExtension::class
];
/**
@ -124,13 +145,11 @@ class Media extends Model
),
'created_at' => [
'type' => 'date',
"format" => "yyyy-MM-dd HH:mm:ss",
// 'fielddata' => true
"format" => "yyyy-MM-dd HH:mm:ss"
],
'updated_at' => [
'type' => 'date',
"format" => "yyyy-MM-dd HH:mm:ss",
// 'fielddata' => true
"format" => "yyyy-MM-dd HH:mm:ss"
],
'version' => [
'type' => 'text',
@ -157,6 +176,92 @@ class Media extends Model
]
);
/**
* Perform any actions required after the model boots.
*
* @return void
*/
protected static function booted()
{
static::created(function (self $model) {
/** @var \App\Models\User */
$user = auth()->user();
MediaCreated::dispatch($user, $model);
/** @throws \RuntimeException */
$model->addToElasticSearch();
});
static::updating(function (self $model) {
if ($model->statut === 0 and $model->arcadia_id) {
throw ValidationException::withMessages([
'statut' => trans('Impossible de changer le statut en brouillon quand la fiche est liée à arcadia')
]);
}
});
static::updated(function (self $model) {
/** @var \App\Models\User */
$user = auth()->user();
// * Prevent soft delete trigerring update event
if (!\array_key_exists('deleted_at', $model->getChanges())) {
MediaUpdated::dispatch($user, $model);
}
if ($model->getRawOriginal('etiquette_id') != $model->etiquette_id) {
/** @var \App\Models\Etiquette|null */
$oldLabel = Etiquette::where('etiquette_id', $model->getRawOriginal('etiquette_id'))->first();
/** @var \App\Models\Etiquette|null */
$newLabel = Etiquette::where('etiquette_id', $model->etiquette_id)->first();
MediaChangedLabel::dispatch($user, $model, $oldLabel, $newLabel);
}
/** @throws \RuntimeException */
$model->addToElasticSearch();
});
static::deleted(function (self $model) {
/** @var \App\Models\User */
$user = auth()->user();
MediaDestroyed::dispatch($user, $model);
/** @throws \RuntimeException */
$model->removeFromElasticSearch();
$model->deleteFilesOnAllPath();
});
}
// * Laravel Behaviors
/**
* Get the prunable model query.
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public function prunable()
{
return static::query();
}
/**
* Prepare the model for pruning.
*
* @return void
* @throws \RuntimeException If pruning the model fails.
*/
protected function pruning()
{
$storage = Storage::disk('media');
if ($storage->exists($this->relative_path) and !$storage->delete($this->relative_path)) {
throw new \RuntimeException("Could not delete $this->relative_path from storage.");
}
if ($storage->exists($this->preview_relative_path) and !$storage->delete($this->preview_relative_path)) {
throw new \RuntimeException("Could not delete $this->preview_relative_path from storage.");
}
if ($storage->exists($this->thumb_relative_path) and !$storage->delete($this->thumb_relative_path)) {
throw new \RuntimeException("Could not delete $this->thumb_relative_path from storage.");
}
}
// * RELATIONSHIPS
/**
@ -182,14 +287,14 @@ class Media extends Model
}
/**
* BelongsTo typemedia relation
* Get the typemedia that owns the media.
* BelongsTo typeMedia relation
* Get the typeMedia that owns the media.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function typemedia()
public function typeMedia()
{
return $this->belongsTo(Typemedia::class, 'typemedia_id');
return $this->belongsTo(TypeMedia::class, 'type_media_id');
}
/**
@ -200,7 +305,7 @@ class Media extends Model
*/
public function typevue()
{
return $this->belongsTo(Typevue::class, 'typevue_id');
return $this->belongsTo(TypeVue::class);
}
/**
@ -211,7 +316,7 @@ class Media extends Model
*/
public function langue()
{
return $this->belongsTo(Langue::class, 'typevue_id');
return $this->belongsTo(Langue::class, 'langue_id');
}
/**
@ -244,7 +349,7 @@ class Media extends Model
*/
public function tags()
{
return $this->belongsToMany(Tag::class, 'medias_tags', 'media_id', 'tag_id');
return $this->belongsToMany(Tag::class, 'media_tag');
}
/**
@ -255,7 +360,7 @@ class Media extends Model
*/
public function articles()
{
return $this->belongsToMany(Article::class, 'medias_articles', 'media_id', 'article_id');
return $this->belongsToMany(Article::class, 'media_article');
}
/**
@ -266,7 +371,7 @@ class Media extends Model
*/
public function societes()
{
return $this->belongsToMany(Societe::class, 'medias_societes', 'media_id', 'societe_id');
return $this->belongsToMany(Societe::class, 'media_societe');
}
/**
@ -277,7 +382,7 @@ class Media extends Model
*/
public function marques()
{
return $this->belongsToMany(Marque::class, 'medias_marques', 'media_id', 'marque_id');
return $this->belongsToMany(Marque::class, 'media_marque', 'media_id', 'marque_id');
}
/**
@ -310,11 +415,339 @@ class Media extends Model
*/
public function paniers()
{
return $this->belongsToMany(Panier::class, 'paniers_medias', 'media_id', 'panier_id');
return $this->belongsToMany(Panier::class);
}
// * METHODS
/**
* Get basename
*
* @return string
*/
public function getBasenameAttribute(): string
{
return "{$this->uid}.{$this->extension->value}";
}
/**
* Get preview_basename
*
* @return string
*/
public function getPreviewBasenameAttribute(): string
{
$extension = match ($this->extension) {
MediaExtension::pdf, MediaExtension::ai, MediaExtension::psd => MediaExtension::png,
default => $this->extension,
};
return "{$this->uid}_preview.{$extension->value}";
}
/**
* Get thumb_basename
*
* @return string
*/
public function getThumbBasenameAttribute(): string
{
$extension = match ($this->extension) {
MediaExtension::pdf, MediaExtension::ai, MediaExtension::psd => MediaExtension::png,
default => $this->extension,
};
return "{$this->uid}_thumb.{$extension->value}";
}
/**
* Get relative_path
*
* @return string
*/
public function getRelativePathAttribute(): string
{
return "{$this->folder}/{$this->basename}";
}
/**
* Get preview_relative_path
*
* @return string
*/
public function getPreviewRelativePathAttribute(): string
{
return "{$this->folder}/{$this->preview_basename}";
}
/**
* Get thumb_relative_path
*
* @return string
*/
public function getThumbRelativePathAttribute(): string
{
return "{$this->folder}/{$this->thumb_basename}";
}
/**
* Get full_path
*
* @return string
*/
public function getFullPathAttribute(): string
{
/** @var \Illuminate\Filesystem\FilesystemAdapter */
$storage = Storage::disk('media');
return $storage->path($this->relative_path);
}
/**
* Get preview_full_path
*
* @return string
*/
public function getPreviewFullPathAttribute(): string
{
/** @var \Illuminate\Filesystem\FilesystemAdapter */
$storage = Storage::disk('media');
return $storage->path($this->preview_relative_path);
}
/**
* Get thumb_full_path
*
* @return string
*/
public function getThumbFullPathAttribute(): string
{
/** @var \Illuminate\Filesystem\FilesystemAdapter */
$storage = Storage::disk('media');
return $storage->path($this->thumb_relative_path);
}
/**
* Delete files on path
*
* @return void
*/
public function deleteFilesOnAllPath()
{
/** @var \Illuminate\Filesystem\FilesystemAdapter */
$storage = Storage::disk('media');
$storage->delete($this->relative_path);
$storage->delete($this->thumb_relative_path);
$storage->delete($this->preview_relative_path);
// TODO: Add delete forl all sujet formats.
}
/**
* Add this media into Elastic Search
*
* @return void
* @throws \RuntimeException If adding to ES failed.
*/
public function addToElasticSearch()
{
$this->removeFromElasticSearch();
try {
$this->refresh();
$this->addToIndex();
} catch (\Exception $e) {
report($e);
throw new \RuntimeException("Failed to add media '$this->arcadia_id' to ES", 0, $e);
}
}
/**
* Remove this media from ElasticSearch
*
* @return void
* @throws \RuntimeException If someting goes wrong.
*/
public function removeFromElasticSearch()
{
$esExist = self::searchByQuery(['match' => ['arcadia_id' => strval($this->arcadia_id)]]);
// * Remove all from elastic if exists
if ($esExist->totalHits() > 0) {
try {
$this->removeFromIndex();
} catch (\Exception $e) {
report($e);
throw new \RuntimeException("Failed to add media '$this->arcadia_id' to ES", 0, $e);
}
}
}
/**
* Create thumbnail image for a Media Subject on very of its formats.
* - Creation des vignettes en lien avec le sujet du média
*
* @return void
* @throws \ImagickException On errors.
* @throws \RuntimeException If media file is missing.
* @phpcs:ignore Squiz.Commenting.FunctionCommentThrowTag.WrongNumber
*/
public function createSubjectThumbnails()
{
/** @var \Illuminate\Filesystem\FilesystemAdapter */
$storage = Storage::disk('media');
if (!$storage->exists($this->relative_path)) {
throw new \RuntimeException("Missing Media file at path '$this->relative_full_path'");
}
$im = new \Imagick();
$im->readImageBlob(
$storage->get($this->relative_path),
$this->basename
);
$im->setImageBackgroundColor('#ffffff');
$im->setImageAlphaChannel(\Imagick::ALPHACHANNEL_REMOVE);
$im->mergeImageLayers(\Imagick::LAYERMETHOD_FLATTEN);
$im->stripImage();
if (in_array($this->extension, [MediaExtension::pdf, MediaExtension::ai, MediaExtension::psd])) {
$im->setIteratorIndex(0);
}
/** @var \Illuminate\Support\Collection<\App\Models\Format> $formats */
$formats = optional($this->sujet)->formats ?? collect();
foreach ($formats as $format) {
$targetWidth = \floatval($format->largeur);
if (\floatval($format->hauteur) == 0) {
$targetHeight = \floatval(floor(($this->hauteur * $format->largeur) / $this->largeur));
} else {
$targetHeight = \floatval($format->hauteur);
}
$im->setImageFormat($format->extension);
if ($this->largeur >= $targetWidth || $this->hauteur >= $targetHeight) {
$im->thumbnailImage($targetWidth, $targetHeight, true);
}
$storage->put(
"{$this->folder}/{$this->uid}_{$format->libelle}.{$format->extension}",
$im->getImageBlob()
);
}
$im->destroy();
unset($im);
}
/**
* Create thumbnail image for a Media.
* - Creation des vignettes de base
*
* @return void
* @throws \ImagickException On errors.
* @throws \RuntimeException If media file is missing.
* @phpcs:ignore Squiz.Commenting.FunctionCommentThrowTag.WrongNumber
*/
public function createThumbnail()
{
/** @var \Illuminate\Filesystem\FilesystemAdapter */
$storage = Storage::disk('media');
if (!$storage->exists($this->relative_path)) {
throw new \RuntimeException("Missing Media file at path '$this->relative_full_path'");
}
$im = new \Imagick();
$im->readImageBlob(
$storage->get($this->relative_path),
$this->basename
);
if (in_array($this->extension, [MediaExtension::pdf, MediaExtension::ai, MediaExtension::psd])) {
$im->setIteratorIndex(0);
}
/*
Handle CMJN - DOESN'T WORK
if ($im->getImageColorspace() === \Imagick::COLORSPACE_CMYK){
$im->transformImageColorspace(\Imagick::COLORSPACE_RGB);
}
*/
// * create preview
/** @var \App\Models\Format $format */
$format = Format::withoutGlobalScope('App\Scopes\SystemScope')
->where('libelle', '=', 'preview')->firstOrFail();
if ($this->extension == MediaExtension::gif) {
if ($this->largeur >= $format->largeur || $this->hauteur >= $format->hauteur || $this->largeur == "") {
$im = $im->coalesceImages();
foreach ($im as $frame) {
$frame->thumbnailImage($format->largeur, $format->hauteur);
$frame->setImagePage($format->largeur, $format->hauteur, 0, 0);
}
$im = $im->deconstructImages();
}
$storage->put(
$this->preview_relative_path,
$im->getImagesBlob()
);
} else {
if ($this->largeur >= $format->largeur || $this->hauteur >= $format->hauteur || $this->largeur == "") {
$im->thumbnailImage($format->largeur, $format->hauteur, true);
}
$storage->put(
$this->preview_relative_path,
$im->getImageBlob()
);
} //end if
// * create thumb
/** @var \App\Models\Format $format */
$format = Format::withoutGlobalScope('App\Scopes\SystemScope')
->where('libelle', '=', 'thumb')->firstOrFail();
if ($this->extension != MediaExtension::png) {
$im->setImageBackgroundColor('#ffffff');
$im->setImageAlphaChannel(\Imagick::ALPHACHANNEL_REMOVE);
$im->mergeImageLayers(\Imagick::LAYERMETHOD_FLATTEN);
$im->stripImage();
}
$im->thumbnailImage($format->largeur, $format->hauteur, true);
$storage->put(
$this->thumb_relative_path,
$im->getImageBlob()
);
$im->destroy();
unset($im);
}
/**
* Renvoi le chemin attendu d'un média selon le format demandé
*
* @param \App\Models\Format $format
* @return string
* @throws \RuntimeException If Format is not handled.
*/
public function getPath(Format $format): string
{
/** @var \Illuminate\Filesystem\FilesystemAdapter */
$storage = Storage::disk('media');
// * format spécifique
if ($format->system) {
if (in_array($this->extension, ['gif', 'jpeg', 'jpg', 'png', 'pdf', 'ai', 'psd'])) {
return $storage->path("/{$this->folder}/{$this->uid}_{$format->libelle}.{$format->extension->value}");
}
return $storage->path($this->relative_path);
}
// * format système (thumb et preview)
if ($format->system) {
if (in_array($this->extension, ['gif', 'jpeg', 'jpg', 'png'])) {
// * Gestion du cas de format qui fixe l'extension.
$file_extension = $format->extension != '' ? $format->extension : $this->extension;
return $storage->path("/{$this->folder}/{$this->uid}_{$format->libelle}.{$file_extension}");
} elseif (in_array($this->extension, ['pdf', 'ai', 'psd'])) {
return $storage->path("/{$this->folder}/{$this->uid}_{$format->libelle}.png");
}
return $storage->path("/{$this->folder}/{$this->uid}.{$this->extension}");
}
throw new \RuntimeException("Unhandled Format $format->id $format->libelle");
}
/**
* Convert the model instance to an array.
*
@ -322,7 +755,15 @@ class Media extends Model
*/
public function toArray()
{
/** @var \Illuminate\Filesystem\FilesystemAdapter */
$storage = Storage::disk('media');
return array_merge(parent::toArray(), [
'size' => ToolboxHelper::formatBytes($this->taille),
'url' => $storage->url($this->relative_path),
'preview_url' => $storage->url($this->preview_relative_path),
'thumb_url' => $storage->url($this->thumb_relative_path),
'jpeg_url' => $storage->url($this->jpeg_relative_path),
'created_at' => $this->created_at->formatLocalized('%Y-%m-%d %H:%M:%S'),
'updated_at' => $this->updated_at->formatLocalized('%Y-%m-%d %H:%M:%S')
]);

View file

@ -58,18 +58,18 @@ class Panier extends Model
*/
public function usersFavoris()
{
return $this->belongsToMany(User::class, 'paniers_users', 'panier_id', 'user_id');
return $this->belongsToMany(User::class);
}
/**
* BelongsToMany medias relation
* The medias that belong to the panier.
* BelongsToMany mediaList relation
* The mediaList that belong to the panier.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function medias()
public function mediaList()
{
return $this->belongsToMany(Media::class, 'paniers_medias', 'panier_id', 'media_id');
return $this->belongsToMany(Media::class, 'panier_media');
}
// * GETTERS
@ -81,7 +81,7 @@ class Panier extends Model
*/
public function getMediacountAttribute(): int
{
return $this->medias()->count();
return $this->mediaList()->count();
}
/**
@ -91,21 +91,13 @@ class Panier extends Model
*/
public function getMediacoverAttribute(): string
{
$cover = '';
if ($media = $this->medias()->where('typemedia_id', 1)->first()) {
switch ($media->typemedia_id) {
case 1:
if ($media->extension == "pdf" || $media->extension == "ai" || $media->extension == "psd") {
$cover = $media->folder . $media->uid . "_thumb.png";
} else {
$cover = $media->folder . $media->uid . "_thumb." . $media->extension;
}
break;
case 2:
$cover = $media->folder . $media->uid . "_thumb." . $media->extension;
break;
}
$media = $this->mediaList()->whereHas('typeMedia', function ($q) {
// * Where type is Photo
$q->where('codeTypemedia', 1);
})->first();
if ($media) {
return $media->thumb_relative_path;
}
return $cover;
return '';
}
}

View file

@ -7,18 +7,37 @@ use Illuminate\Database\Eloquent\Model;
class Recherche extends Model
{
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
'filters' => 'object'
];
// * RELATIONSHIPS
/**
* BelongsTo sujet relation
*
* Get the sujet that owns the recherche.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function sujet()
{
return $this->belongsTo('App\Models\Sujet', 'sujet_id');
return $this->belongsTo(Sujet::class, 'sujet_id');
}
/**
* Get the user that owns the recherche.
* BelongsTo user relation
*
* Get the user that owns the recherche.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function user()
{
return $this->belongsTo('App\Models\User', 'id');
return $this->belongsTo(User::class, 'user_id');
}
}

View file

@ -6,11 +6,17 @@ use Illuminate\Database\Eloquent\Model;
class Societe extends Model
{
// * RELATIONSHIPS
/**
* The medias that belong to the societes.
* BelongsToMany media relation
*
* The media that belong to the societes.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function medias()
public function mediaList()
{
return $this->belongsToMany('App\Models\Media', 'medias_societes', 'societe_id', 'media_id');
return $this->belongsToMany(Media::class);
}
}

View file

@ -13,59 +13,105 @@ class Sujet extends Model
*/
protected $primaryKey = 'codeSujet';
/**
* The users that belong to the sujet.
*/
/**
* Indicates if the IDs are auto-incrementing.
*
* @var boolean
*/
public $incrementing = false;
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
'sujet_dam' => 'bool'
];
// * RELATIONSHIPS
/**
* BelongsToMany users relation
*
* The users that belong to the sujet.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function users()
{
return $this->belongsToMany('App\Models\User', 'sujets_users', 'sujet_id', 'user_id');
return $this->belongsToMany(User::class);
}
/**
* Get the dossier for the sujet.
*/
/**
* HasMany dossiers relation
*
* Get the dossier for the sujet.
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function dossiers()
{
return $this->hasMany('App\Models\Dossier');
return $this->hasMany(Dossier::class);
}
/**
* Get the variantes for the sujet.
*/
/**
* HasMany variantes relation
*
* Get the variantes for the sujet.
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function variantes()
{
return $this->hasMany('App\Models\Variante', 'sujet_id', 'codeSujet');
return $this->hasMany(Variante::class, 'sujet_id', 'codeSujet');
}
/**
* Get the typeVue for the sujet.
*/
/**
* HasMany typeVues relation
*
* Get the typeVue for the sujet.
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function typeVues()
{
return $this->hasMany('App\Models\Typevue', 'sujet_id', 'codeSujet');
return $this->hasMany(TypeVue::class, 'sujet_id', 'codeSujet');
}
/**
* Get the medias for the sujet.
*/
public function medias()
/**
* HasMany media relation
*
* Get the media for the sujet.
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function mediaList()
{
return $this->hasMany('App\Models\Media');
return $this->hasMany(Media::class);
}
/**
* The formats that belong to the sujet.
*/
/**
* BelongsToMany formats relation
*
* The formats that belong to the sujet.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function formats()
{
return $this->belongsToMany('App\Models\Format', 'sujets_formats', 'sujet_id', 'format_id');
return $this->belongsToMany(Format::class, 'sujet_format', 'sujet_id');
}
/**
* Get the recherches for the sujet.
*/
/**
* HasMany recherches relation
*
* Get the recherches for the sujet.
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function recherches()
{
return $this->hasMany('App\Models\Recherche');
return $this->hasMany(Recherche::class);
}
}

View file

@ -6,12 +6,24 @@ use Illuminate\Database\Eloquent\Model;
class Tag extends Model
{
public $timestamps = false;
/**
* The media that belong to the tags.
* Indicates if the model should be timestamped.
*
* @var boolean
*/
public function medias()
public $timestamps = false;
// * RELATIONSHIPS
/**
* BelongsToMany media relation
*
* The media that belong to the tags.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function mediaList()
{
return $this->belongsToMany('App\Models\Media', 'medias_tags', 'tag_id', 'media_id');
return $this->belongsToMany(Media::class);
}
}

83
app/Models/TypeMedia.php Normal file
View file

@ -0,0 +1,83 @@
<?php
namespace App\Models;
use App\Enums\MediaExtension;
use Illuminate\Database\Eloquent\Model;
class TypeMedia extends Model
{
/**
* The primary key associated with the table.
*
* @var string
*/
protected $primaryKey = 'codeTypemedia';
/**
* Indicates if the IDs are auto-incrementing.
*
* @var boolean
*/
public $incrementing = false;
// * RELATIONSHIPS
/**
* HasMany media relation
*
* Get the media for the Typemedia.
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function mediaList()
{
return $this->hasMany(Media::class);
}
// * METHODS
/**
* Undocumented function
*
* @param MediaExtension $extension
* @return self
* @throws \RuntimeException If media type cannot be found.
* @phpcs:disable Squiz.PHP.NonExecutableCode.Unreachable
* @phpcs:disable Generic.Metrics.CyclomaticComplexity.TooHigh
* (switch fall through) .
*/
public static function getMediaType(MediaExtension $extension): self
{
switch ($extension) {
// * Photo (1)
case MediaExtension::gif:
case MediaExtension::jpeg:
case MediaExtension::jpg:
case MediaExtension::png:
case MediaExtension::ai:
case MediaExtension::pdf:
case MediaExtension::psd:
return self::where('codeTypemedia', 1)->first() ?? throw new \RuntimeException(
'Unable to find media type Photo'
);
// * Illustration/Vectorielle (2)
case MediaExtension::svg:
return self::where('codeTypemedia', 2)->first() ?? throw new \RuntimeException(
'Unable to find media type Illustration/Vectorielle'
);
// * Vidéo (3)
case MediaExtension::mp4:
return self::where('codeTypemedia', 3)->first() ?? throw new \RuntimeException(
'Unable to find media type Vidéo'
);
// * Audio (4)
case MediaExtension::mp3:
return self::where('codeTypemedia', 4)->first() ?? throw new \RuntimeException(
'Unable to find media type Vidéo'
);
} //end switch
throw new \RuntimeException("Unhandled extension $extension");
// phpcs:enable
}
}

60
app/Models/TypeVue.php Normal file
View file

@ -0,0 +1,60 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class TypeVue extends Model
{
/**
* The primary key associated with the table.
*
* @var string
*/
protected $primaryKey = 'codeTypevue';
/**
* Indicates if the IDs are auto-incrementing.
*
* @var boolean
*/
public $incrementing = false;
// * RELATIONSHIPS
/**
* HasMany variantes relation
*
* Get the variantes for the Typevue.
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function variantes()
{
return $this->hasMany(Variante::class);
}
/**
* BelongsTo variantes relation
*
* Get the sujet that owns the Typevue.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function sujet()
{
return $this->belongsTo(Sujet::class, 'sujet_id');
}
/**
* HasMany variantes relation
*
* Get the media for the Typevue.
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function mediaList()
{
return $this->hasMany(Media::class);
}
}

View file

@ -1,25 +0,0 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Typemedia extends Model
{
protected $table = "typemedias";
/**
* The primary key associated with the table.
*
* @var string
*/
protected $primaryKey = 'codeTypemedia';
/**
* Get the media for the Typemedia.
*/
public function medias()
{
return $this->hasMany('App\Models\Media');
}
}

View file

@ -1,39 +0,0 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Typevue extends Model
{
/**
* The primary key associated with the table.
*
* @var string
*/
protected $primaryKey = 'codeTypevue';
/**
* Get the variantes for the Typevue.
*/
public function variantes()
{
return $this->hasMany('App\Models\Variante');
}
/**
* Get the sujet that owns the Typevue.
*/
public function sujet()
{
return $this->belongsTo('App\Models\Sujet', 'sujet_id');
}
/**
* Get the medias for the Typevue.
*/
public function medias()
{
return $this->hasMany('App\Models\Media');
}
}

View file

@ -94,7 +94,7 @@ class User extends Authenticatable
*/
public function marques()
{
return $this->belongsToMany(Marque::class, 'marques_users', 'user_id', 'marque_id');
return $this->belongsToMany(Marque::class);
}
/**
@ -105,7 +105,7 @@ class User extends Authenticatable
*/
public function dossiers()
{
return $this->belongsToMany(Dossier::class, 'dossiers_users', 'user_id', 'dossier_id');
return $this->belongsToMany(Dossier::class);
}
/**
@ -116,16 +116,16 @@ class User extends Authenticatable
*/
public function sujets()
{
return $this->belongsToMany(Sujet::class, 'sujets_users', 'user_id', 'sujet_id');
return $this->belongsToMany(Sujet::class, 'sujet_user', 'user_id', 'sujet_id');
}
/**
* HasMany medias relation
* Get the medias for the user.
* HasMany media relation
* Get the media for the user.
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function medias()
public function mediaList()
{
return $this->hasMany(Media::class);
}
@ -160,7 +160,7 @@ class User extends Authenticatable
*/
public function paniersOwner()
{
return $this->hasMany(Panier::class, 'user_id')->with('medias');
return $this->hasMany(Panier::class, 'user_id')->with('mediaList');
}
/**
@ -171,6 +171,6 @@ class User extends Authenticatable
*/
public function paniersFavoris()
{
return $this->belongsToMany(Panier::class, 'paniers_users', 'user_id', 'panier_id');
return $this->belongsToMany(Panier::class);
}
}

View file

@ -13,19 +13,29 @@ class Variante extends Model
*/
protected $primaryKey = 'codeVariante';
// * RELATIONSHIPS
/**
* BelongsTo sujet relation
*
* Get the sujet that owns the variante.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function sujet()
{
return $this->belongsTo('App\Models\Sujet', 'sujet_id');
return $this->belongsTo(Sujet::class);
}
/**
* BelongsTo typeVue relation
*
* Get the typeVue that owns the variante.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function typeVue()
{
return $this->belongsTo('App\Models\Typevue', 'typevue_id');
return $this->belongsTo(TypeVue::class);
}
}

View file

@ -1,21 +0,0 @@
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Broadcast;
use Illuminate\Support\ServiceProvider;
class BroadcastServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Broadcast::routes();
require base_path('routes/channels.php');
}
}

View file

@ -2,6 +2,16 @@
namespace App\Providers;
use App\Events\MediaChangedLabel;
use App\Events\MediaCreated;
use App\Events\MediaUpdated;
use App\Events\MediaDestroyed;
use App\Events\MediaMoved;
use App\Events\MediaSearched;
use App\Listeners\CleanUserOldSearches;
use App\Listeners\SyncWithArcadia;
use App\Listeners\HistorizeMediaEvent;
use App\Listeners\SaveUserSearch;
use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
@ -17,6 +27,27 @@ class EventServiceProvider extends ServiceProvider
Registered::class => [
SendEmailVerificationNotification::class,
],
MediaSearched::class => [
SaveUserSearch::class,
CleanUserOldSearches::class
],
MediaChangedLabel::class => [
HistorizeMediaEvent::class
],
MediaCreated::class => [
HistorizeMediaEvent::class
],
MediaMoved::class => [
HistorizeMediaEvent::class
],
MediaUpdated::class => [
HistorizeMediaEvent::class,
SyncWithArcadia::class
],
MediaDestroyed::class => [
HistorizeMediaEvent::class,
SyncWithArcadia::class
]
];
/**

View file

@ -0,0 +1,65 @@
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
/**
* Custom Rule to validate an enum
*/
class EnumIsValidRule implements Rule
{
/**
* The enum class
*
* @var string
*/
protected string $enum;
/**
* Create a new rule instance
* which validate the fact that a value is within an Enum
*
* @param string $enumClass
* @return void
* @throws \RuntimeException If not a valid enum.
*/
public function __construct(string $enumClass)
{
if (!enum_exists($enumClass)) {
throw new \RuntimeException("'$enumClass' is not an enum");
}
$this->enumClass = $enumClass;
}
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return boolean
* @phpcs:disable Squiz.Commenting.FunctionComment.ScalarTypeHintMissing
* @phpcs:disable Squiz.Commenting.FunctionComment.TypeHintMissing
* @phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter.FoundInImplementedInterfaceBeforeLastUsed
*/
public function passes($attribute, $value): bool
{
// phpcs:enable
try {
return $this->enumClass::tryFrom(\strval($value)) !== false;
} catch (\TypeError) {
return $this->enumClass::tryFrom(\intval($value)) !== false;
}
}
/**
* Get the validation error message.
*
* @return string
*/
public function message(): string
{
return trans('Le champ :attribute doit être une des valeurs suivantes: :values', [
'values' => collect($this->enumClass::cases())->implode(', ')
]);
}
}

View file

@ -68,9 +68,11 @@ class HasMinimumRole implements Rule
* @param mixed $value
* @return boolean
* @phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter.FoundInImplementedInterfaceBeforeLastUsed
* @phpcs:disable Squiz.Commenting.FunctionComment.TypeHintMissing
*/
public function passes($attribute, $value)
{
// phpcs:enable
if (!\ctype_digit(strval($value))) {
return false;
};

Some files were not shown because too many files have changed in this diff Show more