vendor/theatre/core/src/Repository/FilesRepository.php line 974

Open in your IDE?
  1. <?php
  2. namespace TheatreCore\Repository;
  3. use Doctrine\ORM\Query;
  4. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  5. use TheatreCore\Classes\Date\DateTime;
  6. use TheatreCore\Classes\Images\Images;
  7. use TheatreCore\Entity\Bigregions;
  8. use TheatreCore\Entity\Classifications;
  9. use TheatreCore\Entity\Files;
  10. use TheatreCore\Entity\ObjectFile;
  11. use TheatreCore\Entity\Spectacles;
  12. use TheatreCore\Entity\Typesfiles;
  13. use TheatreCore\Traits\TheatreTrait;
  14. use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
  15. use Doctrine\Persistence\ManagerRegistry;
  16. use Symfony\Contracts\Translation\TranslatorInterface;
  17. use App\Service\Functions;
  18. /**
  19.  * FilesRepository
  20.  *
  21.  * This class was generated by the Doctrine ORM. Add your own custom
  22.  * repository methods below.
  23.  */
  24. class FilesRepository extends ServiceEntityRepository
  25. {
  26.     use TheatreTrait {
  27.         getItemsList as protected getItemsListTrait;
  28.     }
  29.     public const UMASK 0002;
  30.     public const FILE_MODE 0664;
  31.     public const DIR_MODE 0775;
  32.     private $em;
  33.     public $__table;
  34.     public $__table_object;
  35.     public $__idtable;
  36.     private $bagInterface;
  37.     public function __construct(ManagerRegistry $registryTranslatorInterface $trImages $imagesFunctions $funcParameterBagInterface $bagInterface)
  38.     {
  39.         parent::__construct($registryFiles::class);
  40.         $this->__table $this->getClassMetadata()->getTableName();
  41.         $this->__table_object $this->getClassMetadata()->name;
  42.         $this->__idtable $this->getClassMetadata()->getSingleIdentifierFieldName();
  43.         $this->bagInterface $bagInterface;
  44.         $this->translator $tr;
  45.         $this->images $images;
  46.         $this->func $func;
  47.     }
  48.     //  {{{ findData()
  49.     /** Recherche des fichiers
  50.      *
  51.      * Permet de rechercher des fichiers en fonction de certains critères :
  52.      * la première lettre, un bout du nom, le type de multimedia, si il est en ligne ou pas
  53.      *
  54.      * @access  public
  55.      * @see     Theatre::find()
  56.      */
  57.     public function findData($publish null$keywords null$idobject null$object null)
  58.     {
  59.         $con $this->getEntityManager();
  60.         $query $con->getRepository(Files::class)->createQueryBuilder('e');
  61.         $query->join('e.idclassification''cl');
  62.         $query->select('e');
  63. //        $query = '
  64. //            SELECT DISTINCT(f.idfile),f.*,tf.*
  65. //            FROM files f
  66. //                JOIN object_file of ON of.`idfile`=f.`idfile`
  67. //                JOIN file_classification fc ON f.`idfile`=fc.`idfile`
  68. //                JOIN classifications cl ON cl.`idclassification`=fc.`idclassification`
  69. //                JOIN typesfiles tf ON tf.`idtype`=f.`idtype`
  70. //            WHERE 1 ';
  71.         // parametre
  72.         if (isset($_REQUEST['idbooklet']) && !empty($_REQUEST['idbooklet'])) {
  73.             $idbooklet $_REQUEST['idbooklet'];
  74.         }
  75.         if (isset($_REQUEST['idtypestructure']) && !empty($_REQUEST['idtypestructure']) && strlen($_REQUEST['idtypestructure']) < 5) {
  76.             $idtypestructure $_REQUEST['idtypestructure'];
  77.         }
  78.         if (isset($_REQUEST['idclassification']) && !empty($_REQUEST['idclassification']) && my_is_int($_REQUEST['idclassification'])) {
  79.             $idclassification $_REQUEST['idclassification'];
  80.         }
  81.         if (isset($_REQUEST['saison']) && !empty($_REQUEST['saison']) && strlen($_REQUEST['saison']) == 9) {
  82.             $saison explode('-'$_REQUEST['saison']);
  83.             $date_start $saison[0] . '-09-01';
  84.             $date_end $saison[1] . '-08-31';
  85.         }
  86.         if (isset($_REQUEST['keywords']) && $_REQUEST['keywords'] != 'nom' && !empty($_REQUEST['keywords'])) {
  87.             $keywords $_REQUEST['keywords'];
  88.         }
  89.         if (isset($_REQUEST['publish']) && !empty($_REQUEST['publish'])) {
  90.             $publish $_REQUEST['publish'];
  91.         }
  92.         if (isset($_REQUEST['valid']) && !empty($_REQUEST['valid'])) {
  93.             $valid $_REQUEST['valid'];
  94.         }
  95.         //recherche stricte par id
  96.         if (!empty($idfile)) {
  97. //            $query .= 'AND  f.`idfile`='.(int)$idbooklet;
  98.             $query->andWhere('f.`idfile`=' . (int)$idbooklet);
  99.         }
  100. //
  101. //        // mots cles
  102.         if (!empty($keywords)) {
  103. //            $query .= ' AND f.`title` LIKE \'%'.$this->escape($keywords).'%\'';
  104.             $query->andWhere(' f.`title` LIKE \'%' $this->escape($keywords) . '%\'');
  105.         }
  106. //
  107. //        // saison
  108.         if (!empty($date_start) && !empty($date_end)) {
  109. //            $query .= ' AND f.`date_start`=\''.$date_start.'\' AND f.`date_end`=\''.$date_end.'\' ';
  110.             $query->andWhere(' f.`datestart`=\'' $date_start '\' AND f.`dateend`=\'' $date_end '\' ');
  111.         }
  112.         // saison
  113.         if (!empty($idclassification)) {
  114. //            $query .= ' AND fc.`idclassification`='.$idclassification.' ';
  115.             $query->andWhere(' fc.`idclassification`=' $idclassification ' ');
  116.         }
  117.         // selectionne les fiches hors ligne
  118.         if (!empty($publish) && $publish == 'no') {
  119. //            $query .= ' AND f.`publish`=0';
  120.             $query->andWhere(' f.`publish`=0');
  121.         }
  122.         // selectionne les fiches non validé
  123.         if (!empty($valid) && $valid == 'no') {
  124. //            $query .= ' AND f.`valid`=0';
  125.             $query->andWhere('f.`valid`=0');
  126.         }
  127.         // selectionne les fiches non validé proposé avec une classification publique
  128.         if (isset($_REQUEST['to_publish'])) {
  129. //            $query .= ' AND f.`publish`=0 AND cl.`is_public`=1';
  130.             $query->andWhere('e.publish=0 AND cl.isPublic=1');
  131.         }
  132.         if (isset($_REQUEST['to_valid'])) {
  133. //            $query .= ' AND f.`valid`=0 AND cl.`is_public`=1';
  134.             $query->andWhere('e.valid=0 AND cl.isPublic=1');
  135.         }
  136.         if ($this->getCount()) {
  137.             $query->select('COUNT(e.idfile)');
  138.             $this->setCount(false);
  139.             return $query;
  140.         }
  141.         // on lance la recherche
  142.         $this->specialQuery($query);
  143.     }
  144.     // }}}
  145.     //  {{{ setToArray()
  146.     /** Liste des multimedias dans un tableau associatif
  147.      *
  148.      * Tableau associatif notament utilisé pour lister les informations sur les multimedias
  149.      * Utile pour générer les tableaux HTML de listes de multimedias
  150.      *
  151.      * @access  public
  152.      * @return  array
  153.      * @see     findData()
  154.      */
  155.     public function setToArray($spec true)
  156.     {
  157.         if ($spec == true) {
  158.             $this->findData();
  159.         }
  160.         $values = array();
  161.         $color null;
  162.         $nb 0;
  163.         while ($this->fetch()) {
  164.             // valeurs de l'enregistrement
  165.             $values[$nb] = $this->getInfosFile($this->idfile);
  166.             // couleur de ligne alternative
  167.             $color $this->colorAlternate($color);
  168.             $values[$nb]['colorline'] = $color;
  169.             $values[$nb]['id'] = $this->idfile;
  170.             $nb++;
  171.         }
  172.         return $values;
  173.     }
  174.     // }}}
  175.     //  {{{ orderByDefaut()
  176.     /** Classement par défaut
  177.      *
  178.      * Défini le tri par défaut pour les requêtes de type SELECT
  179.      *
  180.      * @access public
  181.      * @return string
  182.      */
  183.     public function orderByDefaut($order null)
  184.     {
  185.         // tri par défaut
  186.         if (empty($order)) {
  187.             $order 'dateinsert';
  188.         }
  189.         return $order;
  190.     }
  191.     // }}}
  192.     //  {{{ getInfosFile()
  193.     /** Infos sur un fichier
  194.      *
  195.      * @access   public
  196.      * @param int $idfile id de l'objet
  197.      * @return   array
  198.      */
  199.     public function getInfosFile($idfile null$params_data = array(), $params_display = array())
  200.     {
  201.         $infos = array();
  202.         ////////////// infos de la table
  203.         if (!isset($this->idfile) || empty($this->idfile)) {
  204.             if (!empty($idfile)) {
  205.                 $sql 'SELECT f.*, tf.titre, tf.extension, tf.mime_type, tf.inclus
  206.                         FROM ' $this->__table ' f, typesfiles tf
  207.                         WHERE f.idtype=tf.idtype AND f.idfile=' . (int)$idfile;
  208.                 $infos $this->queryRow($sql);
  209.                 if (empty($infos)) {
  210.                     return array();
  211.                 }
  212.             }
  213.         } else if (!empty($this->datas[$this->currentRow])) {
  214.             $infos $this->datas[$this->currentRow];
  215.         } else {
  216.             $idfile $this->idfile;
  217.             $infos $this->objToArray();
  218.             $query $this->createQueryBuilder('e')
  219.                 ->leftJoin('e.idtype''it')
  220.                 ->select('e')
  221.                 ->addSelect('partial it.{idtype,extension}')
  222.                 ->andWhere('e.idfile = :file')->setParameter(':file'$this->idfile)
  223.                 ->getQuery();
  224.             $infos $query->getResult();
  225.             $infos $query->getSingleResult(Query::HYDRATE_ARRAY);
  226.         }
  227.         // selectionne aussi la/les classification(s)
  228.         $classifications_list $this->getClassifications($idfile);
  229.         if (!empty($classifications_list)) {
  230.             $infos['classifications'] = $classifications_list;
  231.         }
  232.         // ajouter le chemin complet
  233.         if (!empty($infos)) {
  234.             if (!empty($infos['idtype']['extension'])) {
  235.                 $extension $infos['idtype']['extension'];
  236.             } else {
  237.                 $extension $infos['extension'];
  238.             }
  239.             $infos['filepath'] = $_ENV['URL_DIRECTORYUPLOAD'] . strtolower($extension) . '/' $infos['file'];
  240.         }
  241.         // générer la vignette PDF
  242.         if (!empty($infos['idfile'])) {
  243.             $images $this->images;
  244.             if (!empty($infos['idtype']['extension'])) {
  245.                 $extension $infos['idtype']['extension'];
  246.             } else {
  247.                 $extension $infos['extension'];
  248.             }
  249.             $infos['vignette'] = $_ENV['URL_DIRECTORYUPLOAD'] . $extension '/' $images->pdf2thumbnail($infos['file'], $_ENV['PATH_DIRECTORYUPLOAD'] . $extension '/');
  250.             $infos['pdf'] = $_ENV['URL_DIRECTORYUPLOAD'] . $extension '/' $infos['file'];
  251.         }
  252.         // le nom de la structure
  253.         if (!empty($infos['organisation'])) {
  254.             $infos['contacts']['organisation'] = $infos['organisation'];
  255.             $infos['nameview'] = $infos['organisation'] . ' / ' $infos['title'];
  256.         }
  257.         // suite
  258.         foreach (array('url_clean''nom_suite''city') as $f) {
  259.             if (!empty($infos[$f])) {
  260.                 $infos['contacts'][$f] = $infos[$f];
  261.             }
  262.         }
  263.         // valid ?
  264.         if (!empty($infos['valid']) && $infos['valid'] == 1) {
  265.             $infos['valid'] = true;
  266.         }
  267.         // la saison
  268.         if (!empty($infos['date_start']) && !empty($infos['date_end'])) {
  269.             $infos['dateStart'] = new \DateTime($infos['date_start']);
  270.             $infos['dateEnd'] = new \DateTime($infos['date_end']);
  271.         }
  272.         if (!empty($infos['dateStart']) && !empty($infos['dateEnd'])) {
  273.             $date_start_array $infos['dateStart']->format('Y');
  274.             $date_end_array $infos['dateEnd']->format('Y');
  275. //            $date_start_array = explode('-', $infos['dateStart']);
  276. //            $date_end_array = explode('-', $infos['dateEnd']);
  277.             $infos['saison'] = $date_start_array '-' $date_end_array;
  278.             // saison en cours ?
  279.             if ($infos['saison'] == DateTime::getLastSaison()) {
  280.                 $infos['current_saison'] = true;
  281.             }
  282.         }
  283.         //retourner le contenu
  284.         return $infos;
  285.     }
  286.     // }}}
  287.     //  {{{ uploadObjectFile()
  288.     /** Copier en upload et dans la base de données un fichier
  289.      *
  290.      *
  291.      * @access   public
  292.      * @param string $file objet $_FILES[]
  293.      * @param string|array $file_classification le nom/classification du fichier à copier sans extension (ex : biofile)
  294.      * @param string $objet le type d'objet à insérer (personnes, spectacles...)
  295.      * @param string $idobject id de l'utilisateur pour le nom de son répertoire
  296.      * @param array $filedata toutes les données associées au fichier : titre, description...
  297.      * @param string $idfile (id du fichier à modifier si on est en mode modification)
  298.      * @param object $finfo instance d'un objet FileInfo (optionnel)
  299.      * @return   int|bool  false si erreur, id du fichier si ok
  300.      */
  301.     public function uploadObjectFile($file$file_classification$object$idobject$filedata$idfile null$finfo null$extra = array())
  302.     {
  303.         $conn $this->getEntityManager();
  304.         if ($this->my_is_int($file_classification)) {
  305.             $file_classification = array($file_classification);
  306.         }
  307.         if (empty($file_classification)) return false;
  308.         // champs en option
  309.         $fields = array(
  310.             'title',
  311.             'idextranetuser',
  312.             'range',
  313.             'description',
  314.             'copyright',
  315.             'language',
  316.             'idcontent',
  317.             'idfile_original',
  318.             'watermark',
  319.             'date_start',
  320.             'date_end',
  321.             'publishing_date',
  322.             'is_editable',
  323.             'publish',
  324.             'valid'
  325.         );
  326.         $date = new \DateTime();
  327.         // pour la saison
  328.         if (!empty($filedata['saison'])) {
  329.             // transformer la saison en date_start / date_end
  330.             $saison_array explode('-'$filedata['saison']);
  331. //            $filedata['date_start'] = $saison_array[0].'-09-01';
  332. //            $filedata['date_end'] = $saison_array[1].'-08-31';
  333.         }
  334.         if (!empty($filedata['publishing_date']) && !$filedata['publishing_date'] instanceof \DateTime && strpos('/'$filedata['publishing_date']) !== false) {
  335.             $publishing_date explode('/'$filedata['publishing_date']);
  336.             $filedata['publishing_date'] = $date->setDate($publishing_date[2], $publishing_date[1], $publishing_date[0]);
  337.         }
  338.         //répertoire des fichiers (répertoire d'upload)
  339.         $directoryupload $_ENV['PATH_DIRECTORYUPLOAD'];
  340.         //objet dans la table OBJECT_FILE
  341.         $obj_objectfile $conn->getRepository(ObjectFile::class);
  342.         //on a chargé un nouveau fichier que ce soit en modification ou en insertion
  343.         if (is_array($file)
  344.             || (is_object($file) && $file->isSubmitted() && !empty($file->getData()))) {
  345.             static $list_types_mime null;
  346.             if (is_null($list_types_mime)) {
  347.                 // récupére les infos id,mime,extension
  348.                 $sql_mime 'SELECT mime_type,idtype,extension FROM typesfiles WHERE upload=\'oui\'';
  349.                 $list_types_mime $this->queryAll($sql_mime, array(), nulltrue);
  350.                 if (empty($list_types_mime)) {
  351.                     throw new \Exception('chargement impossible des Types Mimes autorisés');
  352.                 }
  353.             }
  354.             // voir si c'est un fichier uploade ou juste un fichier sur le serveur
  355.             if (is_object($file) && $file->isSubmitted()) {
  356.                 //récupérer le type mime du fichier uploadé
  357.                 $typemime $file->getData();
  358.                 //$typemime = $typemime['type'];
  359.                 $typemime $this->func->finfo_file_simple($finfo$typemime->getPathName());
  360.                 $is_objectfile true;
  361.             } else {
  362.                 // recuperer le type mime du fichier sur le serveur
  363.                 $typemime $this->func->finfo_file_simple($finfo$file['file']);
  364.                 $is_simplefile true;
  365.             }
  366.         
  367.             $inListTypeMime false;
  368.             $inListTypeMimeInfo = [];
  369.             foreach($list_types_mime as $key => $element)  {
  370.                 if(in_array($typemime$element)) {
  371.                     $inListTypeMime true;
  372.                     $inListTypeMimeInfo $element;
  373.                     break;
  374.                 }
  375.             }
  376.             // récupére l'id du type MIME et l'extension qui correspondent
  377.             if ($inListTypeMime == true) {
  378.                 $idtypefile $inListTypeMimeInfo['idtype'];
  379.                 $extension $inListTypeMimeInfo['extension'];
  380.             } else {
  381.                 return false;
  382.             }
  383.             // chgt umask
  384.             $oldumask umask();
  385.             if (self::UMASK) {
  386.                 umask(self::UMASK);
  387.             }
  388.             //répertoire des données (repertoire d'upload + extension)
  389.             $directoryupload .= $extension;
  390.             // vérifier si le dossier existe, sinon le créer
  391.             if (!file_exists($directoryupload)) {
  392.                 mkdir($directoryuploadself::DIR_MODEtrue);
  393.             }
  394.             //// uploader le fichier ou le copier
  395.             // nom unique et chemin du nouveau fichier
  396.             do {
  397.                 $nomfichier uniqid('f-' substr(md5($object $idobject), 03) . '-') . '.' $extension;
  398.                 $newfile $directoryupload '/' $nomfichier;
  399.             } while (file_exists($newfile));
  400.             if (isset($is_objectfile)) {
  401.                 $file $file->getData();
  402.                 $uploadok $file->move($directoryupload$nomfichier);
  403.             } else {
  404.                 $uploadok copy($file['file'], $newfile);
  405.             }
  406.             //mettre les bons droits (lecture) pour ce fichier
  407.             if ($uploadok) {
  408.                 chmod($newfileself::FILE_MODE);
  409.             }
  410.             //erreur lors de l'upload du fichier
  411.             if (empty($uploadok)) {
  412.                 throw new \Exception('erreur lors de la mise-en-ligne du fichier');
  413.             }
  414.             // champ ImageDescription ?
  415.             /*$exif = exif_read_data($newfile);
  416.             print_r($exif);
  417.             exit;*/
  418.             // on souhaite un copyright ?
  419.             $extension_img = array('jpg''png''gif');
  420.             if (!empty($filedata['watermark']) && !empty($filedata['copyright']) && in_array($extension$extension_img)) {
  421.                 $images $this->images;
  422.                 $images->setWatermark($newfilenull, array('text' => $filedata['copyright']));
  423.             }
  424.             // supprimer l'ancien fichier et la relation en enlevant le fichier en dur dans le cas d'une modification !
  425.             if (!empty($idfile)) {
  426.                 $this->deleteFile($idfile$object$idobjecttrue);
  427.             }
  428.             // commencer la transaction
  429.             $error null;
  430.             $conn->beginTransaction();
  431.             $new_file = new Files();
  432.             //mise en forme des données
  433.             $idType $conn->getRepository(Typesfiles::class)->find($idtypefile);
  434.             $new_file->setIdtype($idType);
  435.             $new_file->setFile($nomfichier);
  436.             $new_file->setDateStart(new \DateTime('now'));
  437.             // test les champs
  438.             foreach ($fields as $f) {
  439.                 if (!empty($filedata[$f])) {
  440.                     $field implode(''array_map(function ($m) {
  441.                         return ucfirst($m);
  442.                     }, explode('_'$f)));
  443.                     $new_file->{'set' ucfirst($field)}($filedata[$f]);
  444.                 }
  445.             }
  446.             $conn->persist($new_file);
  447.             $conn->flush();
  448.             $conn->commit();
  449.             $idfileinsere $new_file->getIdfile();
  450.             //on insère un nouveau document dans la table file que ce soit une modif ou un insert !
  451.             try {
  452.                 $idfileinsere $new_file->getIdfile();
  453.             } catch (\Exception $e) {
  454.                 $error $e->getError();
  455.                 if ($this->in_transaction) {
  456.                     $this->rollback();
  457.                 }
  458.             }
  459.             // ajout des classifications
  460.             if (empty($error)) {
  461.                 try {
  462.                     $this->setRelationSelect('file_classification''idclassification''idfile'$file_classification$idfileinsere);
  463.                 } catch (\Exception $e) {
  464.                     $error $e->getError();
  465.                     if ($this->in_transaction) {  // annuler la transaction
  466.                         $this->rollback();
  467.                     }
  468.                 }
  469.             }
  470.             if (empty($error)) {
  471.                 //mise en forme des données
  472.                 $conn->beginTransaction();
  473.                 $objectFile = new ObjectFile();
  474.                 $objectFile->setIdobject($idobject);
  475.                 $objectFile->setObject($object);
  476.                 $objectFile->setIdfile($new_file);
  477.                 // on ajoute la liaison avec l'objet
  478.                 try {
  479.                     $conn->persist($objectFile);
  480.                     $conn->flush();
  481.                 } catch (\Exception $e) {
  482.                     $error $e->getError();
  483.                     if ($this->in_transaction) {
  484.                         $this->rollback();
  485.                     }
  486.                 }
  487.                 if (empty($error)) {
  488. //                    if ($this->in_transaction) {
  489.                     $conn->commit();
  490. //                    }
  491.                 }
  492.             }
  493.             if (empty($error)) {
  494.                 // est-ce qu'on a des liaisons en plus ?
  495.                 if (!empty($extra['more_linked_object'])) {
  496.                     foreach ($extra['more_linked_object'] as $k => $v) {
  497.                         //mise en forme des données
  498.                         $values = array(
  499.                             'idobject' => $k,
  500.                             'object' => $v,
  501.                             'idfile' => $idfileinsere
  502.                         );
  503.                         // champ a mettre a jour
  504.                         $obj_objectfile->setUpdateFields($values);
  505.                         // on ajoute la liaison avec l'objet
  506.                         try {
  507.                             $idobjectfile $obj_objectfile->setData(nulltrue);
  508.                         } catch (\Exception $e) {
  509.                             $error $e->getError();
  510.                             if ($this->in_transaction) {
  511.                                 $this->rollback();
  512.                             }
  513.                         }
  514.                         if (empty($error)) {
  515.                             if ($this->in_transaction) {
  516.                                 $this->commit();
  517.                             }
  518.                         }
  519.                     }
  520.                 }
  521.             }
  522.             if (!empty($error)) {
  523.                 // en cas d'erreur lors de l'insertion en bdd, on supprime le fichier uploadé
  524.                 @unlink($newfile);
  525.             }
  526.             // restauration umask
  527.             umask($oldumask);
  528.         } else { //on a pas chargé de nouveau fichier, on fait juste une modification des datas
  529.             //si on a un $idfile c'est que l'on est en modification
  530.             if (!empty($idfile)) {
  531.                 // il faut récupérer les infos de l'ancien fichier
  532.                 $taboldfile $this->queryRow('SELECT * FROM files WHERE files.idfile=' . (int)$idfile);
  533.                 // commencer la transaction
  534.                 $error null;
  535.                 // tableau pour insertion dans la table files
  536.                 $values = array(
  537.                     'idtype' => $taboldfile['idtype'],
  538.                     'file' => $taboldfile['file'],
  539.                     'dateupdate' => $this->func->now()
  540.                 );
  541.                 // test les champs
  542.                 foreach ($fields as $f) {
  543.                     if (!empty($filedata[$f])) {
  544.                         $values[$f] = $filedata[$f];
  545.                     }
  546.                 }
  547.                 if (!empty($values['idextranetuser'])) {
  548.                     $values['idextranetuser'] = $values['idextranetuser']->getIdextranetuser();
  549.                 }
  550.                 if (!empty($values['date_start'])) {
  551.                     $values['date_start'] = $values['date_start']->format('Y-m-d');
  552.                 }
  553.                 if (!empty($values['date_end'])) {
  554.                     $values['date_end'] = $values['date_end']->format('Y-m-d');
  555.                 }
  556.                 if (!empty($values['publishing_date'])) {
  557.                     $values['publishing_date'] = $values['publishing_date']->format('Y-m-d');
  558.                 }
  559.                 // publie ou pas
  560.                 if (!empty($filedata['publish'])) {
  561.                     $values['publish'] = $filedata['publish'];
  562.                 } else {
  563.                     $values['publish'] = 0;
  564.                 }
  565.                 // validé ou pas
  566.                 if (!empty($filedata['valid'])) {
  567.                     $values['valid'] = $filedata['valid'];
  568.                 } else {
  569.                     $values['valid'] = 0;
  570.                 }
  571.                 // champ a mettre a jour
  572.                 $this->setUpdateFields($values);
  573.                 // on update
  574.                 try {
  575.                     $res $this->setData($idfiletrue);
  576.                 } catch (\Exception $e) {
  577.                     $error $e->getError();
  578. //                    if ($this->in_transaction) {
  579. //                        $this->rollback();
  580. //                    }
  581.                 }
  582.                 // ajout des classifications
  583.                 if (empty($error)) {
  584.                     try {
  585.                         $this->setRelationSelect('file_classification''idclassification''idfile'$file_classification$idfile);
  586.                     } catch (\Exception $e) {
  587.                         $error $e->getError();
  588. //                        if($this->in_transaction) {  // annuler la transaction
  589. //                            $this->rollback();
  590. //                        }
  591.                     }
  592.                 }
  593.                 if (empty($error)) {
  594. //                    if ($this->in_transaction) {
  595. //                        $this->commit();
  596. //                    }
  597.                 }
  598.                 // est-ce qu'on a des liaisons en plus ?
  599.                 if (!empty($extra['more_linked_object'])) {
  600.                     // supprimer les anciens et ajouter les nouveaux
  601.                     $sql 'DELETE
  602.                             FROM object_file
  603.                             WHERE idfile=' $idfile '
  604.                             AND idobject!=' $idobject '
  605.                             AND object!=\'' $object '\' ';
  606.                     $this->exec($sql);
  607.                     foreach ($extra['more_linked_object'] as $k => $v) {
  608.                         //mise en forme des données
  609.                         $values = array(
  610.                             'idobject' => $k,
  611.                             'object' => $v,
  612.                             'idfile' => $idfile
  613.                         );
  614.                         // champ a mettre a jour
  615.                         $obj_objectfile->setUpdateFields($values);
  616.                         // on ajoute la liaison avec l'objet
  617.                         try {
  618.                             $idobjectfile $obj_objectfile->setData(nulltrue);
  619.                         } catch (\Exception $e) {
  620.                             $error $e->getError();
  621.                             if ($this->in_transaction) {
  622.                                 $this->rollback();
  623.                             }
  624.                         }
  625.                         if (empty($error)) {
  626.                             if ($this->in_transaction) {
  627.                                 $this->commit();
  628.                             }
  629.                         }
  630.                     }
  631.                 }
  632.                 
  633.                 $idfileinsere $idfile;
  634.             }
  635.         }
  636.         // retourner l'idobject du fichier créé dans la table file
  637.         return $idfileinsere;
  638.     }
  639.     // }}}
  640.     //  {{{ isUseObjectFile()
  641.     /** Vérifier si un fichier est utilisé par un autre contenu
  642.      *
  643.      *
  644.      * @access   public
  645.      * @param int $idfile id du fichier à vérifier
  646.      * @return   bool
  647.      */
  648.     public function isUseObjectFile($idfile)
  649.     {
  650.         // on compte le nb d'utilisation
  651.         $total $this->queryOne('SELECT COUNT(DISTINCT(idobject)) AS total FROM object_file WHERE object_file.idfile=' $idfile);
  652.         //on a au moins 2 enregistrements liés
  653.         if ($total 1) {
  654.             return true;
  655.         }
  656.         return false;
  657.     }
  658.     // }}}
  659.     //  {{{ deleteFile()
  660.     /** Supprimer un fichier sur le serveur
  661.      *
  662.      *
  663.      * @access   public
  664.      * @param string $id id du fichier à supprimer
  665.      * @param string $object type de fichier à supprimer (ex : persons, contacts...)
  666.      * @param string $idobject id de la personne qui possède le fichier
  667.      */
  668.     public function deleteFile($id$object$idobject$delfile)
  669.     {
  670.         //repertoire de l'utilisateur (répertoire d'upload + object + id personne)
  671.         $directoryupload $_ENV['PATH_DIRECTORYUPLOAD'];
  672.         //le fichier n'est pas utilisé, on peut le supprimer
  673.         if (!$this->isUseObjectFile($id)) {
  674.             //récupérer les infos du fichier
  675. //            $this->selectAdd();
  676. //            $this->selectAdd('idtype,file');
  677.             $data $this->find($id);
  678.             $type $data->getIdtype()->getExtension();
  679.             //répertoire
  680.             if (is_object($type)) {
  681.                 $filedelete $directoryupload $type->extension '/' $data->getFile();
  682.             } else {
  683.                 $filedelete null;
  684.             }
  685.             //supprimer le fichier sur le disque
  686.             if (file_exists($filedelete) && $delfile) {
  687.                 // supprimer le fichier principal
  688.                 @unlink($filedelete);
  689.                 // supprimer aussi les vignettes
  690.                 $this->deleteVignettes($id$object$idobject);
  691.             }
  692.             //supprimer l'enregistrement en lui même (table file)
  693.             $this->deleteData($id);
  694.         }
  695.         //dans touts les cas, supprimer l'enregistrement dans la relation object_file
  696.         $this->deleteDataRelation('object_file''idfile'$id'idobject'$idobject'object'$object);
  697.     }
  698.     // }}}
  699.     //  {{{ deleteSimpleFile()
  700.     /** Supprimer un fichier simple sur le serveur
  701.      *
  702.      *
  703.      * @access   public
  704.      * @param string $id id du fichier à supprimer
  705.      */
  706.     public function deleteSimpleFile($idfile)
  707.     {
  708.         //repertoire de l'utilisateur (répertoire d'upload + object + id personne)
  709.         $directoryupload PATH_DIRECTORYUPLOAD;
  710.         $infos $this->getInfosFile($idfile);
  711.         //répertoire
  712.         $filedelete $directoryupload $infos['extension'] . '/' $infos['file'];
  713.         // si c'est un pdf,
  714.         if ($infos['extension'] == 'pdf') {
  715.             $files glob($filedelete '-*.jpg');
  716.             if (!empty($files) && is_array($files)) {
  717.                 foreach ($files as $f) {
  718.                     @unlink($f);
  719.                 }
  720.             }
  721.         }
  722.         //supprimer le fichier sur le disque
  723.         if (file_exists($filedelete)) {
  724.             // supprimer le fichier principal
  725.             @unlink($filedelete);
  726.             // supprimer aussi les vignettes
  727.             $this->deleteVignettes($idfile);
  728.             //supprimer l'enregistrement en lui même (table file)
  729.             $this->deleteData($idfile);
  730.         }
  731.         return true;
  732.     }
  733.     // }}}
  734.     //  {{{ countObjectFiles()
  735.     /** Compter les fichiers lies a un objet
  736.      *
  737.      *
  738.      * @access   public
  739.      * @param string $idobject id de l'objet lié
  740.      * @param string $object le type d'objet (personnes, spectacles...)
  741.      * @param string|int|array $idclassification le rechercher par type de classification
  742.      * @return   array
  743.      * @see Theatre_Classifications::getAssociate())
  744.      */
  745.     public function countObjectFiles($idobject$object 'contents'$idclassification null$extra = array())
  746.     {
  747.         $extra['count_only'] = true;
  748.         return $this->getObjectFiles($idobject$object$idclassification$extra);
  749.     }
  750.     // }}}
  751.     //  {{{ getObjectFiles()
  752.     /** Retourner les fichiers lies a un objet
  753.      *
  754.      *
  755.      * @access   public
  756.      * @param string $idobject id de l'objet lié
  757.      * @param string $object le type d'objet (personnes, spectacles...)
  758.      * @param string|int|array $idclassification le rechercher par type de classification
  759.      * @return   array
  760.      * @see Theatre_Classifications::getAssociate())
  761.      */
  762.     public function getObjectFiles($idobject$object 'contents'$idclassification null$extra = array())
  763.     {
  764.         if (isset($extra['count_only']) && $extra['count_only']) {
  765.             $fields = array();
  766.         } else {
  767.             $fields '*';
  768.         }
  769.         $extra['mode'] = 'file';
  770.         if (!empty($classification) && ($classification == 21 || $classification == 'class_affiche_spec')) {
  771.             // une seule affiche par spectacle !
  772.             $extra['limit'] = '1';
  773.         }
  774.         $classifications $this->getEntityManager()->getRepository(Classifications::class);
  775.         $classifications->setPublishStatus($this->publish_status);
  776.         $tabfile $classifications->getAssociate($idobject$object$idclassification$fields$extra);
  777.         if (!empty($extra['count_only'])) {
  778.             return $tabfile;
  779.         }
  780.         //retourner les données du fichier sous forme de tableau
  781.         if (!empty($tabfile)) {
  782.             $images $this->images;
  783.             $new_tabfile = array();
  784.             $images_extensions = array('jpg''png''gif');
  785.             foreach ($tabfile as $k => $v) {
  786.                 if (empty($v['idfile'])) {
  787.                     dump('revoir cette ligne là 938');
  788.                     break;
  789.                 }
  790.                 $idfile $v['idfile'];
  791.                 // grouper par idfile
  792.                 foreach ($new_tabfile as $kf => $f) {
  793.                     if ($f['idfile'] == $idfile) {
  794.                         $new_tabfile[$kf]['classification_array'] = array(
  795.                             $new_tabfile[$kf]['classification'],
  796.                             $classifications->getObjectTitle($v['idclassification']),
  797.                         );
  798.                         $stop true;
  799.                     }
  800.                 }
  801.                 if (!empty($stop)) {
  802.                     break;
  803.                 }
  804.                 $new_tabfile[$k] = $v;
  805.                 $new_tabfile[$k]['classification'] = $classifications->getObjectTitle($v['idclassification']);
  806.                 $new_tabfile[$k]['logo'] = strtolower($v['extension']) . '.png';
  807.                 $new_tabfile[$k]['publishing_date'] = $v['publishing_date'];
  808.                 if (!empty($v['date_start']) && $v['date_start'] != '0000-00-00 00:00:00' && !empty($v['date_end']) && $v['date_end'] != '0000-00-00 00:00:00') {
  809.                     $date_start_array explode('-'$v['date_start']);
  810.                     $date_end_array explode('-'$v['date_end']);
  811.                     $new_tabfile[$k]['saison'] = $date_start_array[0] . '-' $date_end_array[0];
  812.                     // saison en cours ?
  813.                     if ($new_tabfile[$k]['saison'] == DateTime::getLastSaison()) {
  814.                         $new_tabfile[$k]['current_saison'] = true;
  815.                     }
  816.                 }
  817.                 if (!empty($v['publishing_date']) && $v['publishing_date'] != '0000-00-00') {
  818.                     $new_tabfile[$k]['publishing_date_str'] = $this->getFormeDate($v['publishing_date'], '%d/%m/%Y'true);
  819.                     $new_tabfile[$k]['publishing_date_str_full'] = $this->getFormeDate($v['publishing_date'], '%d %B %Y'true);
  820.                 }
  821.                 $new_tabfile[$k]['dateinsert_str'] = $this->getFormeDate($v['dateinsert'], '%d/%m/%Y'true);
  822.                 $new_tabfile[$k]['dateinsert_str_full'] = $this->getFormeDate($v['dateinsert'], '%d %B %Y'true);
  823.                 // on veut également savoir si ce doc est associé à d'autres choses (par exemple : spectacles)
  824.                 if (!empty($extra['get_objects'])) {
  825.                     $new_tabfile[$k]['objects'] = $this->getObjects($v['idfile'], array('idobject' => $idobject));
  826.                 }
  827.                 if (!empty($extra['get_others'])) {
  828.                     $sql 'SELECT *
  829.                             FROM object_file
  830.                             WHERE idfile=' $v['idfile'] . '
  831.                             AND idobject!=' $idobject;
  832.                     $others $this->queryAll($sql);
  833.                     if (!empty($others)) {
  834.                         $others_tab = array();
  835.                         foreach ($others as $other) {
  836.                             if ($other['object'] != $object) {
  837.                                 $others_tab[$other['object']][$other['idobject']] = $other['idobject'];
  838.                             }
  839.                         }
  840.                     }
  841.                     if (!empty($others_tab['spectacles'])) {
  842.                         $params_sql_spectacle = array(
  843.                             'special' => array(
  844.                                 'idspectacle' => $others_tab['spectacles'],
  845.                                 'publish' => 'all',
  846.                                 'join' => true// jointure gauche avec schedules
  847.                                 'plus_proche' => true,
  848.                             ),
  849.                             'params' => array(
  850.                                 'order' => 's.dateinsert DESC',
  851.                                 'limit' => array(0100),
  852.                                 'where' => ' AND statut!=4',
  853.                             ),
  854.                             'dbg' => array('spectacles_list''Liste des spectacles'),
  855.                         );
  856.                         // affichage
  857.                         $params_display = array(
  858.                             'stylemore' => array('imagep' => 'width:65px''descsp' => 'width:310px;'),
  859.                         );
  860.                         $new_tabfile[$k]['others'][$other['object']] = $this->getEntityManager()->getRepository(Spectacles::class)->getListSpectacles($params_sql_spectacle$params_display);
  861.                     }
  862.                 }
  863.                 // si c'est une image, on le precise
  864.                 if (in_array($v['extension'], $images_extensions)) {
  865.                     $new_tabfile[$k]['is_image'] = true;
  866.                 }
  867.                 // idem pour du son
  868.                 if ($v['extension'] == 'mp3') {
  869.                     $new_tabfile[$k]['is_sound'] = true;
  870.                 }
  871.                 if ($v['extension'] == 'pdf') {
  872.                     if (empty($extra['vignette_width'])) {
  873.                         $extra['vignette_width'] = 120;
  874.                     }
  875.                     $new_tabfile[$k]['vignette'] = $_ENV['URL_DIRECTORYUPLOAD'] . $v['extension'] . '/' $images->pdf2thumbnail($v['file'], $_ENV['PATH_DIRECTORYUPLOAD'] . $v['extension'] . '/'$extra['vignette_width']);
  876.                 }
  877.                 if (!empty($v['language'])) {
  878.                     $new_tabfile[$k]['language_str'] = $this->translator->trans($v['language']);
  879.                 }
  880.                 $new_tabfile[$k]['url_file_path'] = $_ENV['URL_DIRECTORYUPLOAD'] . $v['extension'] . '/' $v['file'];
  881.             }
  882.             // un seul fichier
  883.             if (!empty($extra['idfile']) && !empty($new_tabfile)) {
  884.                 foreach ($new_tabfile as $f) {
  885.                     return $f;
  886.                 }
  887.             }
  888.             return $new_tabfile;
  889.         }
  890.         return null;
  891.     }
  892.     // }}}
  893.     //  {{{ deleteVignettes()
  894.     /** Supprimer les vignettes
  895.      *
  896.      * Supprimer toutes les vignettes d'un fichier
  897.      *
  898.      * @access   public
  899.      * @param string $id id du fichier
  900.      * @param string $objet le type d'objet (personnes, spectacles...)
  901.      */
  902.     public function deleteVignettes($idfile$object 'spectacles'$idobject null$filedata = array(), $thumbsdir 'thumbs')
  903.     {
  904.         $debug false;
  905.         if ($debugfile_put_contents('/tmp/files.txt'"idfile=$idfile object=$object idobject=$idobject\n"FILE_APPEND);
  906.         // retrouver les infos sur le fichier
  907.         if (empty($filedata) && !empty($idfile)) {
  908.             $filedata $this->objToArray($this->get($idfile));
  909.         }
  910.         // parcourir les dossiers thumb et supprimer les vignettes
  911.         $thumbsdir $_ENV['PATH_DIRECTORYUPLOAD'] . $thumbsdir '/';
  912.         if (!empty($filedata['file'])
  913.             && strpos($filedata['file'], '?') === false
  914.             && strpos($filedata['file'], '*') === false
  915.             && is_dir($thumbsdir)) {
  916.             if ($debugfile_put_contents('/tmp/files.txt'"thumbdir=$thumbsdir\n"FILE_APPEND);
  917.             $list $this->func->rglob($filedata['file'], GLOB_NOSORT$thumbsdir'f');
  918.             if ($debugfile_put_contents('/tmp/files.txt'print_r($listtrue), FILE_APPEND);
  919.             foreach ($list as $thumb) {
  920.                 @unlink($thumb);
  921.             }
  922.         }
  923.         $idobject = (int)$idobject;
  924.         if ($idobject && preg_match('/^[a-z0-9_-]+$/'$object)) {
  925.             // repertoire des vignettes
  926.             $vignettes_dir $_ENV['PATH_DIRECTORYUPLOAD'] . $object '/';
  927.             if (is_dir($vignettes_dir)) {
  928.                 if ($debugfile_put_contents('/tmp/files.txt'"dir=$vignettes_dir\n"FILE_APPEND);
  929.                 $list $this->func->rglob('*-' $idobject '.jpg'GLOB_NOSORT$vignettes_dir'f');
  930.                 if ($debugfile_put_contents('/tmp/files.txt'print_r($listtrue), FILE_APPEND);
  931.                 foreach ($list as $vignette) {
  932.                     @unlink($vignette);
  933.                 }
  934.             }
  935.         }
  936.         return true;
  937.     }
  938.     // }}}
  939.     //  {{{ deleteVignettesObject()
  940.     /** Supprime les vignettes d'un objet
  941.      *
  942.      * @access public
  943.      * @param string $object le type d'objet (personnes, spectacles...)
  944.      * @param int $idobject Identifiant de l'enregistrement
  945.      * @param string $classification la classification à supprimer
  946.      * @return bool
  947.      */
  948.     public function deleteVignettesObject($object$idobject$classification)
  949.     {
  950.         // trouver l'idfile associé
  951.         $filedata $this->getAssociateFile($idobject$object$classification);
  952.         return $this->deleteVignettes($filedata$object$idobject$filedata);
  953.     }
  954.     // }}}
  955.     //  {{{ getObjectTitle()
  956.     /** Infos de l'item recherché classification et titre
  957.      *
  958.      * @access public
  959.      * @param int $code Identifiant de l'enregistrement
  960.      * @return string
  961.      */
  962.     public function getObjectTitle($code)
  963.     {
  964.         $sql 'SELECT f.title,cl.classification
  965.                 FROM files f, classifications cl, file_classification fc
  966.                 WHERE f.idfile=' . (int)$code;
  967.         //recuperer la ligne
  968.         $data $this->queryRow($sql);
  969.         if (empty($data)) {
  970.             return null;
  971.         }
  972.         return $data['title'] . ' ' $this->translator->trans($data['classification']);
  973.     }
  974.     // }}}
  975.     //  {{{ getAssociateFile()
  976.     /** Recuperer un fichier associé à un objet
  977.      *
  978.      * @access   public
  979.      * @param int $idobject id de l'objet lié
  980.      * @param string $objet le type d'objet (personnes, spectacles...)
  981.      * @param string|int|array $classification classification recherchee
  982.      * @param array $params_content options supplémentaires (tag=>nom du tag, check_lng=>true|false)
  983.      * @return   array
  984.      * @see Theatre_Classifications::getAssociate())
  985.      */
  986.     public function getAssociateFile($idobject$object$classification$params_content = array())
  987.     {
  988.         $fields '*';
  989.         $extra = array(
  990.             'row' => true,
  991.             'mode' => 'file',
  992.         );
  993.         $conn $this->getEntityManager();
  994.         $classifications $conn->getRepository(Classifications::class);
  995.         $classifications->setPublishStatus($this->publish_status);
  996.         $data $classifications->getAssociate($idobject$object$classification$fields$extra$params_content);
  997.         // ajouter le chemin complet
  998.         if (!empty($data)) {
  999.             $data['filepath'] = $_ENV['URL_DIRECTORYUPLOAD'] . strtolower($data['extension']) . '/' $data['file'];
  1000.             //$data['fileAbsPath'] = PATH_IMG.'upload/'.strtolower($data['extension']).'/'.$data['file'];
  1001.         }
  1002.         //retourner le contenu
  1003.         return $data;
  1004.     }
  1005.     // }}}
  1006.     //  {{{ getRelationsArray()
  1007.     /** Description des relations
  1008.      *
  1009.      * @access  public
  1010.      * @param string|int $type si on souhaite retourner uniquement un type precis
  1011.      * @see     Theatre::getLinkedObject()
  1012.      */
  1013.     public function getRelationsArray($type null)
  1014.     {
  1015.         $array_types = array(
  1016.             'file_classification' => array(// classifications associées
  1017.                 'type_join' => 'multiple',
  1018.                 'dest_table' => 'classifications',
  1019.                 'join_table' => 'file_classification',
  1020.                 'fields' => array('idclassification''classification''type'),
  1021.             ),
  1022.             'file_template' => array(// classifications associées
  1023.                 'type_join' => 'multiple',
  1024.                 'dest_table' => 'templates',
  1025.                 'join_table' => 'file_template',
  1026.                 'fields' => array('idtemplate''description''fichier'),
  1027.             ),
  1028.         );
  1029.         // retourne uniquement un type précis
  1030.         if (!empty($array_types[$type])) {
  1031.             $array_types[$type]['type'] = $type;
  1032.             return $array_types[$type];
  1033.         } else {
  1034.             return $array_types;
  1035.         }
  1036.     }
  1037.     // }}}
  1038.     //  {{{ countAssociateFile()
  1039.     /** compter les fichiers associes par type
  1040.      *
  1041.      * @access   public
  1042.      * @param string|int|array $classification classification recherchee
  1043.      * @param int $idobject id de l'objet lié
  1044.      * @param string $objet le type d'objet (personnes, spectacles...)
  1045.      * @return   array
  1046.      * @see Theatre_Classifications::getAssociate())
  1047.      */
  1048.     public function countAssociateFile($object$idobject$classification)
  1049.     {
  1050.         // string ou int pour classification
  1051.         $classifications $this->getEntityManager()->getRepository(Classifications::class);
  1052.         return $classifications->getAssociate($idobject$object$classification);
  1053.     }
  1054.     // }}}
  1055.     //  {{{ getClassifications()
  1056.     /** récup les classifications d'un fichier
  1057.      *
  1058.      * @access   public
  1059.      * @param int $idfile id du fichier
  1060.      * @return   array
  1061.      */
  1062.     public function getClassifications($idfile)
  1063.     {
  1064.         $conn $this->getEntityManager();
  1065.         $classifications $conn->getRepository(Classifications::class);
  1066.         return $classifications->getObjectClassification($this->__table$idfile$this->getRelationsArray('file_classification'));
  1067.     }
  1068.     // }}}
  1069.     //  {{{ isImage()
  1070.     /** image à afficher
  1071.      *
  1072.      * @access   public
  1073.      * @param string $mime_type Mime type du fichier
  1074.      * @return   array
  1075.      */
  1076.     public function isImage($mime_type)
  1077.     {
  1078.         if ($mime_type == 'image/jpeg'
  1079.             || $mime_type == 'image/png'
  1080.             || $mime_type == 'image/gif') {
  1081.             return true;
  1082.         } else {
  1083.             return false;
  1084.         }
  1085.     }
  1086.     // }}}
  1087.     //  {{{ getFileByUrl()
  1088.     /**
  1089.      * télécharger une image et l'ajouter comme fichier associé
  1090.      *
  1091.      * @access   public
  1092.      * @return   array
  1093.      */
  1094.     function getFileByUrl($image$idclassification$object_infos)
  1095.     {
  1096.         $object $object_infos['object'];
  1097.         $idobject $object_infos['idobject'];
  1098.         $ext strtolower(substr(strrchr($image'.'), 1));
  1099.         // telecharger le fichier dans tmp via wget
  1100.         $image_sortie '/tmp/' uniqid($object $idobject '-') . '.' $ext;
  1101.         $output = array();
  1102.         $return_code = -1;
  1103.         exec('wget -O ' escapeshellarg($image_sortie) . ' ' escapeshellarg($image) . ' 2>&1'$output$return_code);
  1104.         if (!$return_code) {
  1105.             // pas d'erreur
  1106.             //  nom de fichier aléatoire
  1107.             do {
  1108.                 $nomfichier uniqid($object $idobject '-') . '.jpg';
  1109.                 $relfichier 'jpg/' $nomfichier;
  1110.                 $absfichier $_ENV['PATH_DIRECTORYUPLOAD'] . $relfichier;
  1111.                 $nomfichiertmp 'tmp-' $nomfichier;
  1112.                 $relfichiertmp 'jpg/' $nomfichiertmp;
  1113.                 $absfichiertmp $_ENV['PATH_DIRECTORYUPLOAD'] . $relfichiertmp;
  1114.             } while (file_exists($absfichier) || file_exists($absfichiertmp));
  1115.             // conversion en jpg dans un fichier temporaire
  1116.             $output = array();
  1117.             $return_code = -1;
  1118.             exec($_ENV['MAGICK_CONVERT'] . ' ' escapeshellarg($image_sortie) . ' +repage -unsharp 0x0.5 -background white -quality 85 ' escapeshellarg($absfichiertmp) . ' 2>&1'$output$return_code);
  1119.             $ret false;
  1120.             if (!$return_code) {
  1121.                 chmod($absfichiertmpself::FILE_MODE);
  1122.                 // pas d'erreur, on renomme le fichier temporaire
  1123.                 $ret = @rename($absfichiertmp$absfichier);
  1124.             } else {
  1125.                 // on affiche les erreurs
  1126.                 print_r($output);
  1127.             }
  1128.             if (!$ret) {
  1129.                 // on efface le fichier temporaire en cas d'échec
  1130.                 @unlink($absfichiertmp);
  1131.             } else {
  1132.                 // mise à jour de la base
  1133.                 $values = array(
  1134.                     'idtype' => 1,
  1135.                     //'idclassification' => $idclassification,
  1136.                     'file' => $nomfichier,
  1137.                     'title' => $object_infos['title'],
  1138.                     'publish' => 1,
  1139.                     'language' => $object_infos['language'],
  1140.                     'dateinsert' => $this->now(),
  1141.                 );
  1142.                 //objet dans la table OBJECT_FILE
  1143.                 $obj_files $this->getEntityManager()->getRepository(Files::class);
  1144.                 $obj_objectfile $this->getEntityManager()->getRepository(ObjectFile::class);
  1145.                 // commencer la transaction
  1146.                 $error null;
  1147.                 if ($obj_files->supports('transactions')) {
  1148.                     $obj_files->beginTransaction();
  1149.                 }
  1150.                 //champ a mettre a jour
  1151.                 $obj_files->setUpdateFields($values);
  1152.                 $error false;
  1153.                 //on va créer dans la table file le document
  1154.                 try {
  1155.                     $idfileinsere $obj_files->setData(nulltrue);
  1156.                 } catch (\Exception $e) {
  1157.                     $error $e->getError();
  1158.                     if ($obj_files->in_transaction) {
  1159.                         $obj_files->rollback();
  1160.                     }
  1161.                 }
  1162.                 if ($idfileinsere) {
  1163.                     //mise en forme des données
  1164.                     $values = array(
  1165.                         'idobject' => $idobject,
  1166.                         'object' => $object,
  1167.                         'idfile' => $idfileinsere
  1168.                     );
  1169.                     // champ a mettre a jour
  1170.                     $obj_objectfile->setUpdateFields($values);
  1171.                     // on va créer dans la table object_file le document
  1172.                     try {
  1173.                         $idobjectfile $obj_objectfile->setData(nulltrue);
  1174.                     } catch (\Exception $e) {
  1175.                         $error $e->getError();
  1176.                         if ($obj_files->in_transaction) {
  1177.                             $obj_files->rollback();
  1178.                         }
  1179.                     }
  1180.                     // ajouter dans files_classification
  1181.                     $file_classification Theatre::factory('file_classification');
  1182.                     //mise en forme des données
  1183.                     $values = array(
  1184.                         'idclassification' => $idclassification,
  1185.                         'idfile' => $idfileinsere
  1186.                     );
  1187.                     // champ a mettre a jour
  1188.                     $file_classification->setUpdateFields($values);
  1189.                     // on va créer dans la table object_file le document
  1190.                     try {
  1191.                         $file_classification->setData(null);
  1192.                     } catch (\Exception $e) {
  1193.                         $error $e->getError();
  1194.                         if ($obj_files->in_transaction) {
  1195.                             $obj_files->rollback();
  1196.                         }
  1197.                     }
  1198.                     if (empty($error)) {
  1199.                         if ($obj_files->in_transaction) {
  1200.                             $obj_files->commit();
  1201.                         }
  1202.                     } else {
  1203.                         // on efface le fichier image en cas d'échec
  1204.                         @unlink($absfichier);
  1205.                     }
  1206.                 }
  1207.             }
  1208.         }
  1209.     }
  1210.     // }}}
  1211.     //  {{{ getObjects()
  1212.     /**
  1213.      * Trouver les contenus associés à un fichier
  1214.      *
  1215.      * @access   public
  1216.      * @return   array
  1217.      */
  1218.     function getObjects($idfile$not = array())
  1219.     {
  1220.         $conn $this->getEntityManager();
  1221.         $sql 'SELECT *
  1222.                 FROM object_file
  1223.                 WHERE idfile=' $idfile ' ';
  1224.         if (!empty($not['idobject'])) {
  1225.             $sql .= ' AND  idobject!=' $not['idobject'] . ' ';
  1226.         }
  1227.         if (!empty($not['object'])) {
  1228.             $sql .= ' AND  object!=\'' $not['object'] . '\' ';
  1229.         }
  1230.         $results $this->queryAll($sql);
  1231.         $associates = array();
  1232.         if (!empty($results)) {
  1233.             foreach ($results as $r) {
  1234.                 $associates[] = array(
  1235.                     'title' => $conn->getRepository('TheatreCore\Entity\\' $r['object'])->getObjectTitle($r['idobject']),
  1236.                     'url_clean' => $this->getUrlClean($r['idobject'], $r['object']),
  1237.                     'idobject' => $r['idobject'],
  1238.                     'object' => $r['object'],
  1239.                 );
  1240.             }
  1241.         }
  1242.         return $associates;
  1243.     }
  1244.     // }}}
  1245.     //  {{{ getItemsList()
  1246.     /** récup les classifications d'un fichier
  1247.      *
  1248.      * @access   public
  1249.      * @param int $idcontent id du contenu
  1250.      * @return   array
  1251.      */
  1252.     public function getItemsList($idobject null$type$src null)
  1253.     {
  1254.         // trouver les groupe de menu
  1255.         if ($type == 'file_contact') {
  1256.             $sql 'SELECT of.*, c.organisation, c.idcontact
  1257.                     FROM object_file of
  1258.                         JOIN contacts c ON of.idobject=c.idcontact
  1259.                     WHERE
  1260.                         of.object=\'contacts\'
  1261.                         AND of.idfile=' $idobject;
  1262.             $results $this->queryAll($sql);
  1263.             $itemslist = [];
  1264.             if (!empty($results)) {
  1265.                 foreach ($results as $r) {
  1266.                     $itemslist[$r['idcontact']]['id'] = $r['idcontact'];
  1267.                     $itemslist[$r['idcontact']]['view_name'] = $r['organisation'];
  1268.                 }
  1269.             }
  1270.             return $itemslist;
  1271.         }
  1272.         return $this->getItemsListTrait($idobject$type$src);
  1273.     }
  1274.     // }}}
  1275.     //  {{{ getSQLFiles()
  1276.     /** Générer la requete standard pour des fichiers
  1277.      *
  1278.      *
  1279.      * @access   public
  1280.      * @param array $query Les paramètres pour la requete
  1281.      * @param bool $debug afficher la requête TODO
  1282.      * @return   string
  1283.      */
  1284.     public function getSQLFiles($query = array(), $debug false)
  1285.     {
  1286.         $conn $this->getEntityManager();
  1287.         // on prepare les tableaux
  1288.         foreach (array('select''from''where''order''group''limit') as $t) {
  1289.             if (!empty($query[$t])) {
  1290.                 if (!is_array($query[$t])) {
  1291.                     $query[$t][] = $query[$t];
  1292.                 } else {
  1293.                     $query[$t] = $query[$t];
  1294.                 }
  1295.             } else {
  1296.                 $query[$t] = array();
  1297.             }
  1298.         }
  1299.         // champs par défaut
  1300.         $this->addSQLParams('select'$query, array(
  1301.             array('files' => '*'),
  1302.             array('file_classification' => '*'),
  1303.             array('typesfiles' => '*'),
  1304.             array('object_file' => '*')
  1305.         ));
  1306.         $this->addSQLParams('join'$query, array(
  1307.             'files.`idfile`' => 'file_classification.`idfile`',
  1308.             'typesfiles.`idtype`' => 'files.`idtype`',
  1309.             'files.`idfile`' => 'object_file.`idfile`',
  1310.             'file_classification.`idfile`' => 'files.`idfile`',
  1311.         ));
  1312.         // publié ou pas
  1313.         if (empty($query['publish']) && $_ENV['CHECK_IF_ONLINE']) {
  1314.             $this->addSQLParams('where'$query, array(
  1315.                 array('files''publish'1)
  1316.             ));
  1317.         } elseif (!empty($query['publish'])) {
  1318.             $this->addSQLParams('where'$query, array(
  1319.                 array('files''publish'$query['publish'])
  1320.             ));
  1321.         }
  1322.         // pour les contacts
  1323.         // champs par défaut
  1324.         $this->addSQLParams('select'$query, array(
  1325.             array('contacts' => 'url_clean,organisation,nom_suite,city')
  1326.         ));
  1327.         $this->addSQLParams('join'$query, array(
  1328.             'object_file.`idobject`' => 'contacts.`idcontact`',
  1329.         ));
  1330.         $this->addSQLParams('where'$query, array(
  1331.             array('object_file''object''contacts')
  1332.         ));
  1333.         // type de structure
  1334.         if (!empty($query['idtypestructure'])) {
  1335.             $this->addSQLParams('where'$query, array(
  1336.                 array('contacts''idtypestructure'$query['idtypestructure'])
  1337.             ));
  1338.         }
  1339.         if (!empty($query['exclude_idtypestructure'])) {
  1340.             $this->addSQLParams('where'$query, array(
  1341.                 array('contacts''idtypestructure'$query['exclude_idtypestructure'], 'AND''NOT IN')
  1342.             ));
  1343.         }
  1344.         // classification
  1345.         if (!empty($query['idclassification'])) {
  1346.             $this->addSQLParams('where'$query, array(
  1347.                 array('file_classification''idclassification'$query['idclassification'])
  1348.             ));
  1349.         }
  1350.         // région
  1351.         if (!empty($query['area'])) {
  1352.             $bigregions $conn->getRepository(Bigregions::class);
  1353.             $res_area ' AND ' $bigregions->getZipCode($query['area'], 'contacts');
  1354.             if (!$bigregions->getZipCode($query['area'], 'contacts')) {
  1355.                 return false;
  1356.             }
  1357.             $this->addSQLParams('where'$query, array($res_area));
  1358.         }
  1359.         // plauqtettes d'un contact
  1360.         if (!empty($query['idcontacts'])) {
  1361.             $this->addSQLParams('where'$query, array(
  1362.                 array('contacts''idcontact'$query['idcontacts'])
  1363.             ));
  1364.         }
  1365.         // par saison
  1366.         if (!empty($query['saison'])) {
  1367.             // si plusieurs saisons
  1368.             if (is_array($query['saison'])) {
  1369.                 foreach ($query['saison'] as $s) {
  1370.                     $s explode('-'$s);
  1371.                     $sql_where_saison[] = ' (files.`date_start`=\'' $s[0] . '-09-01\' AND files.`date_end`=\'' $s[1] . '-08-31\') ';
  1372.                 }
  1373.                 $this->addSQLParams('where'$query, array(' AND (' implode(' OR '$sql_where_saison) . ') '));
  1374.             } else {
  1375.                 $saison explode('-'$query['saison']);
  1376.                 $this->addSQLParams('where'$query, array(
  1377.                     array('files''date_start'$saison[0] . '-09-01'),
  1378.                     array('files''date_end'$saison[1] . '-08-31'),
  1379.                 ));
  1380.                 $this->addSQLParams('order'$query, array('files.`dateinsert`'));
  1381.                 $this->addSQLParams('direction'$query'DESC');
  1382.             }
  1383.         }
  1384.         // le dernier
  1385.         if (!empty($query['max'])) {
  1386.             $this->addSQLParams('order'$query, array('files.`date_end`'));
  1387.             $this->addSQLParams('limit'$query, array(01));
  1388.         }
  1389.         return $this->getSQLObject($query);
  1390.     }
  1391.     // }}}
  1392.     //  {{{ getListFiles()
  1393.     /** Retourne des listes de fichiers
  1394.      *
  1395.      * Retourne des listes de fichiers au format "standard""
  1396.      *
  1397.      * @access   public
  1398.      * @param array $params_sql paramètre pour la requete SQL
  1399.      * @param array $format_vignette de la vignette si pas standard
  1400.      * @param array $params_display paramètre pour l'affichage
  1401.      * @return   array
  1402.      */
  1403.     public function getListFiles($params_sql null$format_vignette = array(), $params_display = array())
  1404.     {
  1405.         // si pas de tableau
  1406.         if (!isset($params_sql['special'])) {
  1407.             $params_sql['special'] = array();
  1408.         }
  1409.         if (!isset($params_sql['params'])) {
  1410.             $params_sql['params'] = array();
  1411.         }
  1412.         // construction de la requête avec le passage de paramètres
  1413.         $sql $this->getSQLFiles($params_sql);
  1414.         if (!$sql) {
  1415.             return false;
  1416.         }
  1417.         // paramètre de debug
  1418.         $dbg = (empty($params_sql['dbg'])) ? array() : $dbg $params_sql['dbg'];
  1419.         // executer la requete
  1420.         $this->query($sql$dbg);
  1421.         // debug
  1422.         $start_boucle microtime(true);
  1423.         $files = array();
  1424.         // on boucle
  1425.         while ($this->fetch()) {
  1426.             // le total
  1427.             if (!empty($params_sql['count_only'])) {
  1428.                 return $this->total;
  1429.             }
  1430.             $idfile $this->idfile;
  1431.             $files[$idfile] = $this->getInfosFile($idfile, array('all' => true));
  1432.         }
  1433.         // debug de la boucle
  1434.         if ($this->isTraceMode('list_object')) {
  1435.             $this->setTraceInfos(array(
  1436.                 'execution_time_boucle' => microtime(true) - $start_boucle,
  1437.                 'nb_occurence' => count($files),
  1438.                 'dbg' => $dbg,
  1439.             ));
  1440.         }
  1441.         // groupement par saison
  1442.         if (!empty($files) && !empty($params_display['group_by_saison'])) {
  1443.             foreach ($files as $file) {
  1444.                 $files_by_saison[$file['saison']]['saison'] = $file['saison'];
  1445.                 $files_by_saison[$file['saison']]['programmes'][] = $file;
  1446.             }
  1447.             return $files_by_saison;
  1448.         }
  1449.         $this->free();
  1450.         return $files;
  1451.     }
  1452.     // }}}
  1453.     // {{{ getSaisons()
  1454.     /** Trouver les saisons qui ont des programmes
  1455.      *
  1456.      * @access public
  1457.      * @return int
  1458.      */
  1459.     public function getSaisons($params = array())
  1460.     {
  1461.         $sql_annees '
  1462.             SELECT `files`.date_start as `date`, CONCAT_WS(\'-\', YEAR(files.`date_start`), YEAR(files.`date_end`)) as saison, YEAR(files.`date_start`) as annee
  1463.             FROM files
  1464.             WHERE CONCAT_WS(\'-\', YEAR(files.`date_start`), YEAR(files.`date_end`))!=\'0-0\' ';
  1465.         if (!empty($params['start_at'])) {
  1466.             $sql_annees .= ' AND files.`date_start`>=\'' $params['start_at'] . '\' ';
  1467.         }
  1468.         $sql_annees .= '
  1469.             GROUP BY saison
  1470.             ORDER BY saison';
  1471.         $listdates $this->queryAll($sql_annees);
  1472.         // liste des saisons et des années
  1473.         if (empty($listdates)) {
  1474.             return array();
  1475.         } else {
  1476.             return $listdates;
  1477.         }
  1478.     }
  1479.     // }}}
  1480.     //  {{{ getBookletsCurrent()
  1481.     /** Programmes de saison ou le plus récent
  1482.      *
  1483.      *
  1484.      * @access   public
  1485.      * @param integer $idcontact Contact
  1486.      * @return   array
  1487.      */
  1488.     public function getBookletsCurrent($idcontact$get_next false)
  1489.     {
  1490.         // voir si il y a des booklets pour la saison courante
  1491.         $current_saison = \TheatreCore\Classes\Date\DateTime::getLastSaison();
  1492.         $list $this->getListFiles(array(
  1493.             'idcontacts' => $idcontact,
  1494.             'idclassification' => array(112),
  1495.             'saison' => array($current_saison),
  1496.             'dbg' => array('booklet_saison_' $current_saison'Programme de la saison ' $current_saison ' pour le contact ' $idcontact),
  1497.         ));
  1498.         // sinon, le dernier fichier
  1499.         if (empty($list)) {
  1500.             $list $this->getListFiles(array(
  1501.                 'max' => true,
  1502.                 'idcontacts' => $idcontact,
  1503.                 'idclassification' => array(112),
  1504.                 'dbg' => array('booklet_saison''Programme le plus récent pour le contact ' $idcontact),
  1505.             ));
  1506.         } else {
  1507.             // si demandé, vérifier également la saison suivante
  1508.             if ($get_next) {
  1509.                 $current_saison explode('-'$current_saison);
  1510.                 $next_saison = ($current_saison[0] + 1) . '-' . ($current_saison[1] + 1);
  1511.                 $list += $this->getListFiles(array(
  1512.                     'idcontacts' => $idcontact,
  1513.                     'idclassification' => array(112),
  1514.                     'saison' => array($next_saison),
  1515.                     'dbg' => array('booklet_saison_' $next_saison'Programme de la saison ' $next_saison ' pour le contact ' $idcontact),
  1516.                 ));
  1517.             }
  1518.         }
  1519.         // on retourne le premier de la liste
  1520.         if (!empty($list)) {
  1521.             return $list;
  1522.         }
  1523.     }
  1524.     // }}}
  1525.     //  {{{ getBookletsBySaison()
  1526.     /** Les programmes de saison
  1527.      *
  1528.      *
  1529.      * @access   public
  1530.      * @param array $saison La saison
  1531.      * @param integer $idcontact Le contact
  1532.      * @return   string
  1533.      */
  1534.     public function getBookletsBySaison($saison$idcontact)
  1535.     {
  1536.         $list $this->getListFiles(array(
  1537.             'saison' => $saison,
  1538.             'idcontacts' => $idcontact,
  1539.             'idclassification' => array(112),
  1540.             'dbg' => array('booklet_saison''Programmes de la saison ' $saison ' pour le contact ' $idcontact),
  1541.         ));
  1542.         // on retourne le premier de la liste
  1543.         if (!empty($list)) {
  1544.             return $list;
  1545.         }
  1546.     }
  1547.     // }}}
  1548.     public function getExtension()
  1549.     {
  1550.         if ($this->hasFile()) {
  1551.             echo 'ok';
  1552.             exit;
  1553.         }
  1554.     }
  1555. }