<?php
namespace TheatreCore\Repository;
use App\Service\Calendar;
use TheatreCore\Entity\Bigregions;
use TheatreCore\Entity\Contacts;
use TheatreCore\Entity\Schedules;
use TheatreCore\Traits\TheatreTrait;
use TheatreCore\Entity\Spectacles;
use DateTime;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Mapping;
/**
* SchedulesRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class SchedulesRepository extends ServiceEntityRepository
{
use TheatreTrait {
getRelationsArray as protected getRelationsArrayTrait;
getLinkedObject as protected getLinkedObjectTrait;
}
private $em;
public $__table;
public $__table_object;
public $__idtable;
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Schedules::class);
$this->__table = $this->getClassMetadata()->getTableName();
$this->__table_object = $this->getClassMetadata()->name;
$this->__idtable = $this->getClassMetadata()->getSingleIdentifierFieldName();
}
// {{{ getInfosSchedules()
/** Informations sur une date
*
* @access public
* @return array les infos sous forme de tableau
* @param int $idschedule numero de la fiche date
*/
public function getInfosSchedules($idschedule=null,$params_data=array(),$params_display=array())
{
$conn = $this->getEntityManager();
$infos = array();
////////////// infos de la table
if(!isset($this->idschedule) || empty($this->idschedule)) {
if(!empty($idschedule)) {
$datas = $this->get($idschedule);
dump($this->get($idschedule));
exit;
if(!$this->get($idschedule)) {
return array();
} else {
$infos = $this->objToArray();
}
}
} else {
$infos = $this->datas[$this->rows-1];
$idschedule = $infos['idschedule'];
}
// retourne aussi les infos sur le spectacle lié
$infos['spectacles'] = array(
'title' => $conn->getRepository(Spectacles::class)->getObjectTitle($this->idspectacle),
'idspectacle' => $this->idspectacle,
);
return $infos;
}
// }}}
// {{{ getItemsList()
/** Liste des items pour les champs relationnels
*
* Retourne un tableau associatif contenant la liste des items
* d'une relation. Exemple : getItemsList(4,'text_author'); retourne les noms
* et prénom des auteurs du texte numéro 4
*
* @access public
* @return array
* @param string $type Ce qu'on recherche
* @param string $idtext L'id de l'objet
*/
public function getItemsList($id,$type)
{
// on peux avoir passé juste l'idcontact ou idcontact+idspectacle
if($this->my_is_int($id)) {
$idcontact = $id;
} else {
$ids = unserialize($id);
$idcontact = $ids['idcontact'];
$idspectacle = $ids['idspectacle'];
}
// if(!in_array($type,$this->array_types)) {
if(!$this->getRelationsArray($type)) {
return 'Aucune fonction de recherche pour le type <strong>'.$type.'</strong> dans la méthode !';
}
// requête commune
$sql = 'SELECT c.idcontact, sc.idcontact_festival, c.lastname, c.firstname, c.organisation as view_name
FROM schedules sc
JOIN contacts c ON sc.'.$type.'=c.idcontact
WHERE sc.idcontact='.$idcontact;
// spectacle
if(!empty($idspectacle)) {
$sql .= ' AND sc.idspectacle='.$idspectacle;
}
$sql .= ' GROUP BY c.idcontact';
$datas = $this->queryAll($sql,array(),null,true);
return $datas;
}
// }}}
// {{{ getDatesHours()
/** Dates et heures du spectacle
*
* @access public
* @return array
* @param int $idspectacle identifiant du spectacle
* @param int $idcontact identifiant du contact
*/
public function getDatesHours($idspectacle,$idcontact,$type=null,$version='old') {
if($version=='old') {
return $this->getDatesHoursOld($idspectacle,$idcontact,$type);
} else {
return $this->getDatesHoursNew($idspectacle,$idcontact,$type);
}
}
// }}}
// {{{ getDatesHoursOld()
/** Dates et heures du spectacles
*
* @access public
* @return array
* @param int $idspectacle identifiant du spectacle
* @param int $idcontact identifiant du contact
*/
public function getDatesHoursOld($idspectacle,$idcontact,$type=null)
{
$query = 'SELECT DISTINCT(date), note, is_cancelled, url_spectacle, url_booking, idextranetuser, publish, valid
FROM schedules
WHERE idspectacle='.$idspectacle.'
AND idcontact='.$idcontact.' ';
// pour les dates futurs, commencer au début du mois
if(!empty($type) && $type!='tous') {
if ($type == 'demain') {
$expr = '>=';
$date_search = date('Y-m-01');
} else {
$expr = '<=';
$date_search = date('Y-m-d');
}
$query .= ' AND date'.$expr.'\''.$date_search.'\' ';
}
// classement
$query .= ' ORDER BY date';
$res = $this->query($query);
$nbresult = $this->numRows(); //$res->numRows();
if($nbresult>1) {
$dateshours['periode'] = true;
}
$i = 0;
foreach($res AS $row) { //$res->numRows()
// année mois
$y = $this->getFormeDate($row['date'],"%y",true);
$m = $this->getFormeDate($row['date'],"%m",true);
// format string ou classique
$date_str = $this->getFormeDate($row['date'],"%a %d/%m/%y",true);
$date_orig = $this->getFormeDate($row['date'],$GLOBALS['format_date'][$GLOBALS['lng']]);
$dateshours[$date_orig]['idextranetuser'] = $row['idextranetuser'];
// bidouille pour avoir à valider des heures en plus
if(!isset($dateshours[$date_orig]['valid'])) {
$dateshours[$date_orig]['valid'] = $row['valid'];
} else {
if($row['valid']==0) {
$dateshours[$date_orig]['valid'] = $row['valid'];
}
}
$dateshours[$date_orig]['publish'] = $row['publish'];
// une période
if($nbresult>1) {
$dateshours[$date_orig]['hours'] = $this->getHours($row['date'],$idspectacle,$idcontact);
if($type=='demain' && empty($date_debut_ok)) {
if($row['date']>=date('Y-m-d')) {
$dateshours[$date_orig]['datedebut'] = $date_str;
$date_debut_ok = true;
}
} else {
if($i==0) { // première date = date de début
$dateshours[$date_orig]['datedebut'] = $date_str;
}
}
if($i==$nbresult-1) {
$dateshours[$date_orig]['datefin'] = $date_str;
}
} else { // inde date unique
$dateshours['date'] = $date_orig;
$dateshours['hours'] = $this->getHours($row['date'],$idspectacle,$idcontact);
}
if((empty($dateshours['is_cancelled']) || !$dateshours['is_cancelled']) && $row['is_cancelled']){
$dateshours['is_cancelled'] = (int)$row['is_cancelled'];
}
$hour_string = array();
if(!empty($dateshours[$date_orig]['hours'])) {
foreach($dateshours[$date_orig]['hours'] as $k=>$v) {
if(!empty($v['hour'])) {
$hour_string[] = $v['hour'];
}
}
}
// plusieurs heures ou une seule
if(!empty($hour_string)) {
$hour_string = join(' / ', $hour_string);
} else {
$hour_string = null;
}
$dateshours['event'][$row['date']] = array(
'date' => $row['date'],
'hour' => $hour_string,
'is_cancelled' => $row['is_cancelled'],
'valid' => $row['valid'],
'publish' => $row['publish'],
'idextranetuser' => $row['idextranetuser'],
);
$dateshours['months'][$y.$m] = array('y' => $y, 'm' => $m);
if(!empty($row['note'])) {
$dateshours['event'][$row['date']]['note'] = $row['note'];
}
if(!empty($row['url_spectacle'])) {
$dateshours['event'][$row['date']]['url_spectacle'] = $row['url_spectacle'];
}
if(!empty($row['url_booking'])) {
$dateshours['event'][$row['date']]['url_booking'] = $row['url_booking'];
}
$i++;
}
$this->free(); //$res->free()
// classement months
ksort($dateshours['months']);
ksort($dateshours['event']);
/*
print_r($dateshours);
exit;
*/
return $dateshours;
}
// }}}
// {{{ getDatesHoursNew()
/** Dates et heures du spectacle
*
* @access public
* @return array
* @param int $idspectacle identifiant du spectacle
* @param int $idcontact identifiant du contact
*/
public function getDatesHoursNew($idspectacle,$idcontact,$type=null)
{
$query = 'SELECT DISTINCT(date), note, url_spectacle, url_booking, idextranetuser, publish, valid, is_cancelled
FROM schedules
WHERE idspectacle='.$idspectacle.'
AND idcontact='.$idcontact.' ';
// pour les dates futurs, commencer au début du mois
if(!empty($type) && $type!='tous') {
if ($type == 'demain') {
$expr = '>=';
$date_search = date('Y-m-01');
} else {
$expr = '<=';
$date_search = date('Y-m-d');
}
$query .= ' AND date'.$expr.'\''.$date_search.'\' ';
}
// classement
$query .= ' ORDER BY date';
$res = $this->query($query);
// combien de jours de pause pour définir une période ?
$nbperiode = 15;
$periode = 0; // pour l'incrémentation des périodes
// grouper par période
foreach($res AS $row) {
// détection du changement de période
if(!empty($current_date)) {
// date courante dans la boucle
$date1 = new DateTime($current_date);
$date2 = new DateTime($row['date']);
$interval = $date1->diff($date2);
$diff = $interval->format('%a');
if($diff>$nbperiode) {
$periode++;
}
}
// format string ou classique
$date_str = $this->getFormeDate($row['date'],"%a %d/%m/%y",true);
$date_orig = $this->getFormeDate($row['date'],$GLOBALS['format_date'][$GLOBALS['lng']]);
$dateshours[$periode][$date_orig] = array(
'idextranetuser' => $row['idextranetuser'],
'valid' => $row['valid'],
'publish' => $row['publish'],
'date_str' => $date_str,
'date_orig' => $date_orig,
'is_cancelled' => $row['is_cancelled'],
);
// pour les horaires
$dateshours[$periode][$date_orig]['hours'] = $this->getHours($row['date'],$idspectacle,$idcontact);
// les passer en string
$hour_string = array();
$hours_array = array();
if(!empty($dateshours[$periode][$date_orig]['hours'])) {
// pour les horaires en ligne (rassemblement de toutes les dates de la journée en une seule ligne)
foreach($dateshours[$periode][$date_orig]['hours'] as $k=>$v) {
if(!empty($v['hour'])) {
$hour_string[] = $v['hour'];
}
}
$hours_value = array();
// pour les horaires en groupes (rassemblement de toutes les informations en tableau pour chaque date)
foreach($dateshours[$periode][$date_orig]['hours'] as $k=>$v) {
$key = key($v);
$hours_value[$key] = $v[$key];
if(array_key_exists('url_booking',$v)) {
$hours_array[] = $hours_value;
$hours_value = array();
}
}
}
// plusieurs heures ou une seule
if(!empty($hour_string)) {
$hour_string = join(' / ', $hour_string);
} else {
$hour_string = null;
}
// année et mois
$y = $this->getFormeDate($row['date'],"%y",true);
$m = $this->getFormeDate($row['date'],"%m",true);
$dateshours[$periode]['months'][$y.$m] = array(
'y' => $y,
'm' => $m
);
// les evenements pour Calendar
$dateshours[$periode]['event'][$row['date']] = array(
'date' => $row['date'],
'hour' => $hour_string, //les heures de toute la journée en une seule "ligne"
'hours' => $hours_array, //Un tableau de toutes les heures qui les rassembles par "groupe"
'valid' => $row['valid'],
'publish' => $row['publish'],
'idextranetuser' => $row['idextranetuser'],
'is_cancelled' => $row['is_cancelled'],
);
if(!empty($row['note'])) {
$dateshours[$periode]['event'][$row['date']]['note'] = $row['note'];
}
if(!empty($row['url_spectacle'])) {
$dateshours[$periode]['event'][$row['date']]['url_spectacle'] = $row['url_spectacle'];
}
if(!empty($row['url_booking'])) {
$dateshours[$periode]['event'][$row['date']]['url_booking'] = $row['url_booking'];
}
if(isset($row['is_cancelled'])) {
$dateshours[$periode]['event'][$row['date']]['is_cancelled'] = $row['is_cancelled'];
}
$current_date = $row['date'];
}
$this->free(); //$res->free();
foreach($dateshours as $periode=>$infos) {
// classement months et event
ksort($dateshours[$periode]['months']);
ksort($dateshours[$periode]['event']);
// est-ce une période ou une seule date ?
if(count($infos['event'])>1) {
$dateshours[$periode]['periode'] = 1;
// date de début de période
if($type=='demain') {
// parcourir les dates pour marquer la date qui fait le début de la période
foreach($infos['event'] as $k=>$v) {
if($v['date']>=date('Y-m-d')) {
$date_orig = $this->getFormeDate($v['date'],$GLOBALS['format_date'][$GLOBALS['lng']]);
break;
}
}
} else {
foreach($infos['event'] as $k=>$v) {
$date_orig = $this->getFormeDate($v['date'],$GLOBALS['format_date'][$GLOBALS['lng']]);
break;
}
}
// la date début marquée
$dateshours[$periode][$date_orig]['datedebut'] = $dateshours[$periode][$date_orig]['date_str'];
// date de fin = dernière date
$i = 1;
foreach($infos['event'] as $k=>$v) {
if(!isset($dateshours[$periode]['warning']) && $v['is_cancelled']){
$dateshours[$periode]['warning'] = true;
}
if($i==count($infos['event'])) {
$date_orig = $this->getFormeDate($v['date'],$GLOBALS['format_date'][$GLOBALS['lng']]);
$dateshours[$periode][$date_orig]['datefin'] = $dateshours[$periode][$date_orig]['date_str'];
}
$i++;
}
// une seule date
} else {
// si une seule date
foreach($infos as $kd=>$vd) {
if(!empty($vd['date_orig'])) {
$dateshours[$periode]['date'] = $vd['date_orig'];
$dateshours[$periode]['is_cancelled'] = $vd['is_cancelled'];
$dateshours[$periode]['hours'] = $vd['hours'];
break;
}
}
}
} // fin de la boucle sur les périodes
/*
print_r($dateshours);
exit;
*/
return $dateshours;
}
// }}}
// {{{ getHours()
/** heures du spectacle
*
* @access public
* @return array
* @param string $date La date du spectacle
* @param int $idspectacle identifiant du spectacle
* @param int $idcontact identifiant du contact
*/
public function getHours($date,$idspectacle,$idcontact)
{
$query = 'SELECT hour,note,url_spectacle,url_booking
FROM schedules
WHERE date="'.$date.'" AND idspectacle='.$idspectacle.' AND idcontact='.$idcontact;
$res = $this->query($query);
foreach($res AS $row) { //TODO à revoir -> res->fetchRow()
if($row['hour']!='00:00') {
$hour[]['hour'] = $row['hour'];
}
$hour[]['note'] = $row['note'];
$hour[]['url_spectacle'] = $row['url_spectacle'];
$hour[]['url_booking'] = $row['url_booking'];
}
$this->free(); //res->free();
return $hour;
}
// }}}
// {{{ getDateBySpectaclesCommon()
/** Code commun à getDateBySpectaclesDemain() et getDateBySpectaclesHier(),
* Liste des dates pour une biographie
*
*
* @param string $type demain|hier
* @param int $idspectacle
* @param string $limit
* @param string $order ASC|DESC
* @access protected
* @return array
*/
public function getDateBySpectaclesCommon($type='demain',$idspectacle,$limit,$order,$version='old',$params=array())
{
$conn = $this->getEntityManager();
if ($type == 'demain') {
$expr = '>=';
} elseif($type == 'tous') {
$expr = 'tous';
} else {
$expr = '<=';
}
$query = 'SELECT DISTINCT(s.idschedule),hour,date,s.note,s.url_spectacle,s.url_booking,s.idcontact_festival,s.hour,s.idspectacle,
c.idcontact,c.organisation,c.phone1,c.phone2,c.city,c.url_clean,
ft.idcontact as festival_idcontact,ft.organisation as festival_organisation,ft.city as festival_city,ft.url_clean as festival_url_clean
FROM schedules s
JOIN contacts c ON s.idcontact=c.idcontact
LEFT JOIN contacts ft ON s.idcontact_festival=ft.idcontact
WHERE 1';
if (empty($idspectacle)) {
return false;
}
if(is_array($idspectacle)){
$query .= ' AND s.idspectacle IN ('.implode(',', $idspectacle).')';
}
else{
$query .= ' AND s.idspectacle = '.(int)$idspectacle;
}
if(!in_array($expr, ['premiere_representation', 'tous'])) {
$query .= ' AND s.date'.$expr.'\''.date('Y-m-d').'\'';
}
if(!empty($params['idcontact'])) {
$query .= ' AND c.idcontact = '.$params['idcontact'].' ';
}
$query .= ' ORDER BY s.date '.$order; //GROUP BY c.idcontact
if(!empty($limit)) {
$query .= ' LIMIT 0,'.((int)$limit);
}
if(!empty($params['count'])){
return $this->queryOne($query);
}
//executer la requete
$this->query($query);
//tableau de retour
$r = array();
// pour le contact
$contacts = $conn->getRepository(Contacts::class);
$fields_contact_select = array('idschedule', 'city','url_clean','idcontact','organisation','phone1','phone2','hour','date','idspectacle');
//trouver la date de fin pour chaque spectacle
while ($this->fetch()) {
$idschedule = $this->idschedule;
$date = $this->date;
if(empty($r[$date])){
$r[$date]['date_str'] = $this->getFormeDate($date,"%a %d/%m/%y",true);
$r[$date]['date_full_str'] = $this->getFormeDate($date,"%A %d %B %Y",true);
$r[$date]['date_orig'] = $this->getFormeDate($date,$GLOBALS['format_date'][$GLOBALS['lng']]);
}
if(!empty($this->hour)){
$r[$date]['hour'] = $this->hour;
}
foreach ($fields_contact_select as $f) {
if (isset($this->$f)) {
$r[$date]['datas'][$idschedule][$f] = $this->$f;
}
}
}
if(!empty($params['premiere_representation'])) {
foreach ($r AS $idschedule => $v) {
if (empty($r[$idschedule]['premiere_date'])) {
if (isset($r[$idschedule]['dateshours']['event'])) {
if (is_array($r[$idschedule]['dateshours']['event'])) {
$premiere_date = key($r[$idschedule]['dateshours']['event']);
} else {
$premiere_date = $r[$idschedule]['dateshours']['event'];
}
} else {
if (is_array($r[$idschedule]['dateshours'])) {
//on cherche à ignorer la clé "periode" du tableau "dateshours"
foreach ($r[$idschedule]['dateshours'] AS $kv => $vv) {
if ($kv != 'periode') {
$schedule_date = $kv;
break;
}
}
$premiere_date = $schedule_date;
} else {
$premiere_date = $r[$idschedule]['dateshours'];
}
}
$r[$idschedule]['premiere_date'] = $this->getFormeDate($premiere_date, "%A %d %B %Y", true);
}
}
}
return $r;
}
// }}}
// {{{ getDateBySpectaclesDemain()
/** Dates pour un spectacle
*
* Liste des dates pour un spectacle
*
* @access public
* @return array
* @param int $idspectacle identifiant du spectacle
* @param string $limit limit de l'affichage
* @param string $order ASC|DESC, par défaut ASC
*/
public function getDateBySpectaclesDemain($idspectacle,$limit=null,$order=null,$version='old',$params = [])
{
// ordre de tri
if (empty($order) || strtolower($order) == 'asc') {
$order = 'ASC';
} else {
$order = 'DESC';
}
return $this->getDateBySpectaclesCommon('demain',$idspectacle,$limit,$order,$version,$params);
}
// }}}
// {{{ getDateBySpectaclesHier()
/** Dates pour un spectacle
*
* Liste des dates pour un spectacle
*
* @access public
* @return array
* @param int $idspectacle identifiant du spectacle
* @param string $limit limit de l'affichage
* @param string $order ASC|DESC, par défaut DESC
*/
public function getDateBySpectaclesHier($idspectacle,$limit=null,$order=null,$version='old')
{
//ordre de tri
if (empty($order) || strtolower($order) == 'desc') {
$order = 'DESC';
} else {
$order = 'ASC';
}
return $this->getDateBySpectaclesCommon('hier',$idspectacle,$limit,$order,$version);
}
// }}}
// {{{ getDateLieuCommon()
/** Code commun à getDateLieuDemain() et getDateLieuHier(),
* Liste des dates pour un spectacle
*
*
* @param string $type demain|hier
* @param int $idspectacle
* @param string $limit
* @param string $order ASC|DESC
* @access protected
* @return array
*/
public function getDateLieuCommon($type='demain',$idspectacle,$limit,$order,$version='old',$params=array())
{
$conn = $this->getEntityManager();
if ($type == 'demain') {
$expr = '>=';
} elseif($type == 'tous') {
$expr = 'tous';
} else {
$expr = '<=';
}
// pour débug
if(isset($_REQUEST['group_date_version'])) {
$version = 'new';
}
//récupérer les informations et la date de début
$query = 'SELECT DISTINCT(s.idschedule),s.note,s.url_spectacle,s.url_booking,s.idcontact_festival,s.hour,
c.idcontact,c.organisation,c.phone1,c.phone2,c.city,c.url_clean,MIN(s.date) AS datedebut,
ft.idcontact as festival_idcontact,ft.organisation as festival_organisation,ft.city as festival_city,ft.url_clean as festival_url_clean
FROM schedules s
JOIN contacts c ON s.idcontact=c.idcontact
LEFT JOIN contacts ft ON s.idcontact_festival=ft.idcontact
WHERE s.idspectacle='.((int)$idspectacle);
if(!in_array($expr, ['premiere_representation', 'tous'])) {
$query .= ' AND s.date'.$expr.'\''.date('Y-m-d').'\'';
}
$query .= ' GROUP BY c.idcontact ORDER BY s.date '.$order;
if(!empty($limit)) {
$query .= ' LIMIT 0,'.((int)$limit);
}
//setDebug($query);
//executer la requete
$datas = $this->query($query);
//tableau de retour
$r = array();
// pour le contact
$contacts = $conn->getRepository(Contacts::class);
$fields_contact_select = array('city','url_clean','idcontact','organisation','phone1','phone2' );
//trouver la date de fin pour chaque spectacle
foreach($datas AS $data) {
$this->loadResult($data);
$idschedule = $this->idschedule;
foreach($fields_contact_select as $f) {
if(isset($this->$f)) {
$r[$idschedule][$f] = $this->$f;
}
}
// booking et page du spectacle
if(!empty($this->url_booking)) {
if(preg_match('#^https?://#', $this->url_booking)) {
$r[$idschedule]['url_booking'] = $this->url_booking;
} else {
$r[$idschedule]['url_booking'] = 'http://'.$this->url_booking;
}
}
if(!empty($this->url_spectacle)) {
if(preg_match('#^https?://#', $this->url_booking)) {
$r[$idschedule]['url_spectacle'] = $this->url_spectacle;
} else {
$r[$idschedule]['url_spectacle'] = 'http://'.$this->url_spectacle;
}
}
// voir si le contact à un avatar
$profilepicture = $contacts->getVignetteContact($this->idcontact,array('width' => 40, 'height' => 40),'class_pp');
if(strpos($profilepicture, 'normal-def')===false) {
$r[$idschedule]['profilepicture'] = $profilepicture;
}
if(isset($this->festival_organisation) && $this->festival_organisation!='') {
$r[$idschedule]['festival'] = array(
'organisation' => $this->festival_organisation,
'idcontact' => $this->festival_idcontact,
'url_clean' => $this->festival_url_clean,
);
}
$r[$idschedule]['dateshours'] = $this->getDatesHours($idspectacle,$this->idcontact,$type,$version);
// pour Old
if($version=='old') {
$r[$idschedule]['event'] = $r[$idschedule]['dateshours']['event'];
$r[$idschedule]['months'] = $r[$idschedule]['dateshours']['months'];
// ne pas encombrer le tableau
if(!empty($r[$idschedule]['dateshours']['months'])) {
unset($r[$idschedule]['dateshours']['months']);
}
if(!empty($r[$idschedule]['dateshours']['event'])) {
unset($r[$idschedule]['dateshours']['event']);
}
// générer le calendrier
// première date
foreach($r[$idschedule]['event'] as $k=>$v) {
$calendar = new Calendar($v['date']);
break;
}
// highlight les dates
$i = 0;
foreach($r[$idschedule]['months'] as $k=>$v) {
if($i>0) {
$calendar = new Calendar($v['y'].'-'.$v['m'].'-01');
}
$calendar->highlighted_dates = $r[$idschedule]['event'];
$calendar->link_days = 2;
$calendar->formatted_link_to = "javascript:;";
$r[$idschedule]['calendar'][] = $calendar->output_calendar();
$i++;
}
} // fin test old
}
$this->free();
// pour la nouvelle présentatiopn par période
if($version=='new') {
foreach($r as $k=>$v) {
$kp = 0;
foreach($v['dateshours'] as $kb=>$vb) {
$key = $k.'-'.$kp;
$kp++;
$r[$key] = $v;
unset($r[$k]);
$r[$key]['dateshours'] = $vb;
$r[$key]['event'] = $r[$key]['dateshours']['event'];
$r[$key]['months'] = $r[$key]['dateshours']['months'];
// ne pas encombrer le tableau
if(!empty($r[$key]['dateshours']['months'])) {
unset($r[$key]['dateshours']['months']);
}
if(!empty($r[$key]['dateshours']['event'])) {
unset($r[$key]['dateshours']['event']);
}
// générer le calendrier
// première date
foreach($r[$key]['event'] as $kc=>$vc) {
$calendar = new Calendar($vc['date']);
break;
}
// highlight les dates
$i = 0;
foreach($r[$key]['months'] as $kc=>$vc) {
if($i>0) {
$calendar = new Calendar($vc['y'].'-'.$vc['m'].'-01');
}
$calendar->highlighted_dates = $r[$key]['event'];
$calendar->link_days = 2;
$calendar->formatted_link_to = "javascript:;";
$r[$key]['calendar'][] = $calendar->output_calendar();
$i++;
}
}
}
}
foreach($r AS $key => $data){
$r[$key]['is_cancelled'] = array_search(1, array_column($r[$key]['dateshours'], 'is_cancelled'));
}
if(!empty($params['premiere_representation'])) {
foreach ($r AS $idschedule => $v) {
if (empty($r[$idschedule]['premiere_date'])) {
if (isset($r[$idschedule]['dateshours']['event'])) {
if (is_array($r[$idschedule]['dateshours']['event'])) {
$premiere_date = key($r[$idschedule]['dateshours']['event']);
} else {
$premiere_date = $r[$idschedule]['dateshours']['event'];
}
} else {
if (is_array($r[$idschedule]['dateshours'])) {
//on cherche à ignorer la clé "periode" du tableau "dateshours"
foreach ($r[$idschedule]['dateshours'] AS $kv => $vv) {
if ($kv != 'periode') {
$schedule_date = $kv;
break;
}
}
$premiere_date = $schedule_date;
} else {
$premiere_date = $r[$idschedule]['dateshours'];
}
}
$r[$idschedule]['premiere_date'] = $this->getFormeDate($premiere_date, "%A %d %B %Y", true);
}
}
}
//retourner le tableau
return $r;
}
// }}}
// {{{ getDateLieuDemain()
/** Dates pour un spectacle
*
* Liste des dates pour un spectacle
*
* @access public
* @return array
* @param int $idspectacle identifiant du spectacle
* @param string $limit limit de l'affichage
* @param string $order ASC|DESC, par défaut ASC
*/
public function getDateLieuDemain($idspectacle,$limit=null,$order=null,$version='old')
{
// ordre de tri
if (empty($order) || strtolower($order) == 'asc') {
$order = 'ASC';
} else {
$order = 'DESC';
}
return $this->getDateLieuCommon('demain',$idspectacle,$limit,$order,$version);
}
// }}}
// {{{ getDateLieuHier()
/** Dates pour un spectacle
*
* Liste des dates pour un spectacle
*
* @access public
* @return array
* @param int $idspectacle identifiant du spectacle
* @param string $limit limit de l'affichage
* @param string $order ASC|DESC, par défaut DESC
*/
public function getDateLieuHier($idspectacle,$limit=null,$order=null,$version='old')
{
//ordre de tri
if (empty($order) || strtolower($order) == 'desc') {
$order = 'DESC';
} else {
$order = 'ASC';
}
return $this->getDateLieuCommon('hier',$idspectacle,$limit,$order,$version);
}
// }}}
// {{{ ScheduleToKeywords()
/** Génère une liste de mots clés basés sur les lieux et dates de représentation
*
*
* @param array $schedule
* @param int $max nb max de dates
* @access public
* @return string
*/
function ScheduleToKeywords($schedule, $max=20) {
return null;
require_once PATH_LIBS.'/Functions/Months.php';
// ajout des mots clés basés sur les lieux et dates de représentation
$keywords = array();
$count = 0;
foreach($schedule as $item) {
$count++;
if (!empty($item['city'])) $keywords[] = trim($item['city']);
if (!empty($item['organisation'])) $keywords[] = trim($item['organisation']);
if (isset($item['dateshours']['periode'])) {
foreach ($item['dateshours'] as $k => $v) {
if ($k == 'periode' || $k == 'event' || $k=='months') continue;
$date = explode('/',$k);
$keywords[] = getDay($date[1]); //mois
$keywords[] = $date[2]; // annee
}
} else {
$date = explode('/',$item['dateshours']['date']);
$keywords[] = getDay($date[1]); //mois
$keywords[] = $date[2]; //annee
}
if ($count > $max) break;
}
return implode(' ',array_unique($keywords));
}
// }}}
// {{{ deleteSchedule()
/** Supprimer toutes les dates pour un spectacle et/ou un lieu
*
*
* @param int $idspectacle Identifiant du spectacle
* @param int $idcontact Identifiant du contact
* @access public
* @return array
*/
public function deleteSchedule($idspectacle,$idcontact=null)
{
$sql = 'DELETE FROM '.$this->__table.'
WHERE idspectacle='.(int)$idspectacle;
if(!empty($idcontact)) {
$sql .= ' AND idcontact='.(int)$idcontact;
}
$this->logDeletion('[Schedules::deleteSchedule] Supprime un calendrier '.$sql);
return $this->execute($sql);
}
// }}}
// {{{ cancelledDates()
/** Annulée les dates d'un spectacle
*
*
* @param int $idspectacle Identifiant du spectacle
* @param int $idcontact Identifiant du contact
* @access public
* @return array
*/
public function cancelledDates($idspectacle,$idcontact=null, $status = true)
{
$sql = 'UPDATE schedules
SET is_cancelled = '.(int)$status.',dateupdate=\''.$this->now().'\'
WHERE idspectacle='.(int)$idspectacle .' ';
if(!empty($idcontact)) {
$sql .= ' AND idcontact='.(int)$idcontact;
}
return $this->execute($sql);
}
// }}}
// {{{ validateSchedule()
/** Valider les dates d'un spectacle
*
*
* @param int $idspectacle Identifiant du spectacle
* @param int $idcontact Identifiant du contact
* @access public
* @return array
*/
public function validateSchedule($idspectacle,$idcontact=null)
{
$sql = 'UPDATE schedules
SET publish=1,valid=1,dateupdate=\''.now().'\'
WHERE idspectacle='.(int)$idspectacle;
if(!empty($idcontact)) {
$sql .= ' AND idcontact='.(int)$idcontact;
}
return $this->execute($sql);
}
// }}}
// {{{ countDates()
/** Compter les dates pour un spectacle
*
*
* @param int $idspectacle Identifiant du spectacle
* @access public
* @return array
*/
public function countDates($idspectacle=null,$idcontact=null,$special=array())
{
$sql[] = 'SELECT COUNT(*) as nb
FROM '.$this->__table.' WHERE 1 ';
if(!empty($idspectacle)) {
$sql[] = ' AND idspectacle='.(int)$idspectacle;
}
if(!empty($idcontact)) {
$sql[] = ' AND idcontact='.(int)$idcontact;
}
if(array_key_exists('saison',$special)) {
$s = explode('-', $special['saison']);
$sql[] = ' AND date BETWEEN \''.$s[0].'-09-01\' AND \''.$s[1].'-08-31\' ';
}
$nb = $this->queryOne(join("\n", $sql));
if($nb) {
return $nb;
} else {
return null;
}
}
// }}}
// {{{ getSQLSchedules()
/** Générer la requete standard pour des calendrier
*
* $params = array(
* 'select' => champs en plus pour le select,
* 'from' => champs en plus pour le from,
* 'where' => paramètres en plus le where,
* 'order' => classement des résultats,
* 'limit' => limiter le nb de résultats array(debut,fin), (all pour pas de limit)
* )
*
* @access public
* @param array $query Les paramètres pour la requete
* @param bool $debug afficher la requête
* @return string
*/
public function getSQLSchedules($query=array(),$debug=false)
{
// on prepare les tableaux
foreach(array('select','from','where','order','group','having','limit') as $t) {
if(!empty($query[$t])) {
if(!is_array($query[$t])) {
$query[$t][] = $query[$t];
} else {
$query[$t] = $query[$t];
}
} else {
$query[$t] = array();
}
}
// champs par défaut
if(empty($query['count_only'])) {
$this->addSQLParams('select',$query,array(
array($this->__table => '*')
));
}
else{
$this->addSQLParams('from',$query,array(
'schedules',
));
}
// recherche par région
if(!empty($query['special']['regions'])) {
$this->addSQLParams('from',$query,array(
'contacts',
));
// jointure entre les 3 tables
$this->addSQLParams('join',$query,array(
'contacts.idcontact' => 'schedules.idcontact',
));
// $this->addSQLParams('where',$query,array(
// array('contacts','',$query['special']['regions'], 'AND','IN'),
// ));
}
if(array_key_exists('idsschedules', $query)) {
$query['where'][] = ' AND schedules.idschedule IN ('.implode(',', $query['idsschedules']).') ';
}
if(array_key_exists('saison', $query)) {
$s = explode('-', $query['saison']);
$query['where'][] = ' AND schedules.date BETWEEN \''.$s[0].'-09-01\' AND \''.$s[1].'-08-31\' ';
}
// publié ou pas
if(empty($query['publish']) && $_ENV['CHECK_IF_ONLINE']) {
$this->addSQLParams('where',$query,array(
array($this->__table,'publish',1)
));
} elseif(!empty($query['publish'])) {
$this->addSQLParams('where',$query,array(
array($this->__table,'publish',$query['publish'])
));
}
// validé ou pas
if(isset($query['valid'])) {
$this->addSQLParams('where',$query,array(
array($this->__table,'valid',$query['valid'])
));
}
return $this->getSQLObject($query);
}
// }}}
// {{{ getListSchedules()
/** Retourne des listes de dates
*
* Retourne des listes de date au format "standard""
*
* @access public
* @return array
* @param array $params_sql paramètre pour la requete SQL
* @param array $format_vignette de la vignette si pas standard
* @param array $params_display paramètre pour l'affichage
*/
public function getListSchedules($params_sql=null,$format_vignette=array(),$params_display=array())
{
// construction de la requête avec le passage de paramètres
$sql = $this->getSQLSchedules($params_sql);
// paramètre de debug
$dbg = (empty($params_sql['dbg'])) ? array() : $dbg = $params_sql['dbg'];
// executer la requete
$this->query($sql,$dbg);
$videos = array();
// debug
$start_boucle = microtime(true);
$results = array();
if(!empty($params_sql['count_only']) || !empty(!empty($params_sql['count_only']))){
$results = 0;
}
$color = null;
// on boucle
while($this->fetch()) {
// le total
if(!empty($params_sql['count_only'])) {
return $this->total;
}
$idschedule = $this->idschedule;
$results[$idschedule] = $this->getInfosSchedules($idschedule);
// couleur de ligne alternative
$color = $this->colorAlternate($color);
$results[$idschedule]['colorline'] = $color;
}
// debug de la boucle
if($this->isTraceMode('list_object')) {
$this->setTraceInfos(array(
'execution_time_boucle' => microtime(true) - $start_boucle,
'nb_occurence' => count($dvds),
'dbg' => $dbg,
));
}
$this->free();
return $results;
}
// }}}
// {{{ getSchedule()
/** récupèrer le calendrier d'un spectacle
*
* Récupèrer simplement le calendrier d'un spectacle
*
* @access public
* @return array
* @param int $idspectacle Identifiant du spectacle
*/
public function getSchedule($idspectacle,$api=false)
{
$conn = $this->getEntityManager();
$sql = "SELECT schedules.*, contacts.organisation, contacts.url_clean, contacts.city, contacts.zip, UPPER(contacts.country) AS country, departements.nom AS departement
FROM schedules
INNER JOIN contacts ON contacts.idcontact = schedules.idcontact
INNER JOIN spectacles ON schedules.idspectacle = spectacles.idspectacle
LEFT JOIN departements ON contacts.country LIKE 'FR' AND departements.departement LIKE SUBSTRING(contacts.zip, 1, IF(SUBSTRING(contacts.zip, 1, 2) >= 97, 3, 2))
WHERE schedules.idspectacle = " . (int)$idspectacle . "
AND spectacles.publish = 1 AND spectacles.valid = 1;";
$bigregions = $conn->getRepository(Bigregions::class);
$sql .= ' WHERE schedules.idspectacle='.(int)$idspectacle;
// uniquement les dates validées et les spectacles en ligne et validés
$sql .= ' AND spectacles.publish=1 AND spectacles.valid=1 ';
$dates = $this->queryAll($sql);
// parcourir => grouper les heures par dates
foreach($dates as $k=>$v) {
$key = $v['date'].'-'.$v['url_clean'];
// si la date existe déjà, on ajoute l'heure
if(!empty($rows[$key])) {
$rows[$key]['hours'][] = array(
'hour' => $v['hour'],
);
if(!empty($v['comment'])) {
$rows[$key]['hours']['comment'] = $v['comment'];
}
} else {
$deptCode = $v['zip'] !== null
? substr($v['zip'], 0, 2)
: null;
$rows[$key] = array(
'date' => $v['date'],
'hours' => array(array(
'hour' => $v['hour'],
)),
'location' => array(
'name' => $v['organisation'],
'city' => $v['city'],
'area_code' => $bigregions->getIdbigregionByZip($v['zip']),
'department' => $v['departement'],
'dept_code' => $deptCode,
'zip_code' => $v['zip'],
'country' => $v['country'],
'object' => $v['url_clean'],
'permanent_url' => $_ENV['URL_THNET'].'/contacts/'.$v['url_clean'].'/',
)
);
if(!empty($v['comment'])) {
$rows[$key]['hours']['comment'] = $v['comment'];
}
if(!empty($v['url_spectacle'])) {
$rows[$key]['location']['url_spectacle'] = $v['url_spectacle'];
}
if(!empty($v['url_booking'])) {
$rows[$key]['location']['url_booking'] = $v['url_booking'];
}
/* ancienne version
// si la date existe déjà, on ajoute l'heure
if(!empty($rows[$v['date']])) {
$rows[$v['date']]['hours'][] = array(
'hour' => $v['hour'],
);
if(!empty($v['comment'])) {
$rows[$v['date']]['hours']['comment'] = $v['comment'];
}
} else {
$rows[$v['date']] = array(
'date' => $v['date'],
'hours' => array(array(
'hour' => $v['hour'],
)),
'location' => array(
'name' => $v['organisation'],
'city' => $v['city'],
'object' => $v['url_clean'],
'permanent_url' => $_ENV['URL_THNET'].'/contacts/'.$v['url_clean'].'/',
)
);
if(!empty($v['comment'])) {
$rows[$v['date']]['hours']['comment'] = $v['comment'];
}
if(!empty($v['url_spectacle'])) {
$rows[$v['date']]['location']['url_spectacle'] = $v['url_spectacle'];
}
if(!empty($v['url_booking'])) {
$rows[$v['date']]['location']['url_booking'] = $v['url_booking'];
}
*/
// pour l'api
if($api) {
//$rows[$v['date']] = $this->getApiTab($rows[$v['date']]);
}
}
}
return $rows;
}
// }}}
// {{{ getObjectTitle()
/** Infos de l'item recherché
*
* Affichage standard du titre de l'objet
*
* @access public
* @return string
* @param int $idobject Identifiant de l'item
* @param array $infos_object Informations pour construire le titre
* @param array $params Paramétres supplémentaires
*/
public function getObjectTitle($idobject=null,$infos_object=array(),$params=array())
{
$title = '';
if(!$idobject) {
$idobject = $this->iddvd;
}
// champs
$fields = array('iddvd','title','url_clean');
if(!empty($infos_object)) {
foreach($fields as $k=>$v) {
if(array_key_exists($v, $infos_object)) {
$$v = $infos_object[$v];
}
}
} else {
//charger les infos que si necessaire
if(empty($this->title)) {
$this->selectAdd();
$this->selectAdd(implode(',', $fields));
$this->get($idobject);
}
foreach($fields as $k=>$v) {
if(isset($this->$v) && $this->$v!='') {
$$v = trim($this->$v);
}
}
}
return $title;
}
// }}}
// {{{ getApiTab()
/** génére la version pour la diffusion API
*
* @see Theatre::getApiTab
*/
public function getApiTab($data)
{
// généré à partir de getApiFields
$data_api = parent::getApiTab($data,$_ENV['URL_THNET']);
return $data_api;
}
// }}}
// {{{ getApiFields()
/** champs à renvoyer par l'API ==> NON UTILISÉ
*
* @access public
* @param array tableau de données
*/
protected function getApiFields()
{
return array(
'date' => 'date',
'hours' => array(
'hour' => 'hour',
'comment' => 'comment',
),
'location' => array(
'url_clean' => 'permanent_url#(.*)#'.$_ENV['URL_THNET'].'/contacts/${1}/',
'organisation' => 'name', // ne garder que l'année
),
);
}
// }}}
// {{{ getRelationsArray()
/** Tableau des relations
*
* @access public
* @param string|int $type le type de champ
*/
public function getRelationsArray($type=null)
{
// récupérer les relations communes
$array_types = $this->getRelationsArrayTrait('all');
$array_types += array(
'idcontact' => array(
'type_join' => 'simple',
'dest_table' => 'contacts',
'src_table_field' => 'idcontact',
'join_field_src' => 'idcontact',
'dest_table_field' => 'idcontact',
'fields' => array('idcontact','organisation','url_clean'),
'silent_delete_relation' => true,
'description' => 'Contact associé à ce calendrier',
),
'idcontact_festival' => array(
'type_join' => 'simple',
'dest_table' => 'contacts',
'src_table_field' => 'idcontact',
'join_field_src' => 'idcontact_festival',
'dest_table_field' => 'idcontact',
'fields' => array('idcontact','organisation','url_clean'),
'silent_delete_relation' => true,
'description' => 'Festival associé à ce calendrier',
),
);
if(!empty($array_types[$type])) {
$array_types[$type]['type'] = $type;
return $array_types[$type];
} else {
return $array_types;
}
}
// }}}
// {{{ countSchedules()
/** Compter les dates
*
* @access public
* @return int
*/
public function countSchedules($params = array())
{
$sql = 'SELECT COUNT(*) as nb
FROM '.$this->__table.'
WHERE 1 ';
if(!empty($params['date_start'])) {
$sql .= ' AND date>\''.$params['date_start'].'\' ';
}
try {
return $this->queryOne($sql);;
} catch (\Throwable $e) {
return null;
}
}
// }}}
// {{{ getContactsBySpectaclesSchedules()
/** Récupèrer les contacts de calendrier de spectacles
*
* @access public
* @param int|array $idspectacle le(s) spectacle(s)
* @return array
*/
public function getContactsBySpectaclesSchedules($idspectacle)
{
$sql = 'SELECT c.* FROM
schedules sc
JOIN contacts c ON c.idcontact=sc.idcontact
WHERE
idspectacle IN ('.$this->arrayToIn($idspectacle).')';
$contacts = $this->queryAll($sql);
if(!empty($contacts)) {
return $contacts;
} else {
return array();
}
}
// }}}
}