<?php
namespace TheatreCore\Repository;
use AmazonCloudFront;
use AmazonS3;
use TheatreCore\Classes\Images\Images;
use TheatreCore\Entity\Bigregions;
use TheatreCore\Entity\Files;
use TheatreCore\Entity\News;
use TheatreCore\Entity\Newschedules;
use TheatreCore\Traits\TheatreTrait;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* NewsRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class NewsRepository extends ServiceEntityRepository
{
use TheatreTrait {
deleteData as protected deleteDataTrait;
}
private $em;
public $__table;
public $__table_object;
public $__idtable;
public function __construct(ManagerRegistry $registry, Images $images)
{
parent::__construct($registry, News::class);
$this->__table = $this->getClassMetadata()->getTableName();
$this->__table_object = $this->getClassMetadata()->name;
$this->__idtable = $this->getClassMetadata()->getSingleIdentifierFieldName();
$this->images = $images;
}
/** Recherche des actualités
*
* recherche des actualités postées par les utilisateurs
*
* @access public
* @see Theatre::find()
*/
public function findData($idnew = null, $params = array())
{
$query = $this->createQueryBuilder('e');
if ($this->getCount()) {
$query->select('COUNT(e.idnew)');
$this->setCount(false);
return $query;
}
// parametre
if (!empty($_REQUEST[$this->__idtable]) && my_is_int($_REQUEST[$this->__idtable])) {
$idnew = (int)$_REQUEST[$this->__idtable];
}
if (isset($_REQUEST['keywords']) && $_REQUEST['keywords'] != 'titre') {
$keywords = filter_var(trim($_REQUEST['keywords']));
}
if (isset($_REQUEST['city']) && $_REQUEST['city'] != 'ville' && !empty($_REQUEST['city'])) {
$city = filter_var(trim($_REQUEST['city']));
}
//
// $query = 'SELECT DISTINCT(n.idnew), n.*, e.login, ns.*,n.idnew as idnew
// FROM '.$this->__table.' n
// INNER JOIN extranetusers e ON n.idextranetuser=e.idextranetuser
// LEFT JOIN newschedules ns ON n.idnew=ns.idnew ';
// // également par personnes
// if(!empty($params['persons_list'])) {
// $query .= ' INNER JOIN new_person np ON np.idnew=n.idnew ';
// }
//
// // également par spectacles
// if(!empty($params['spectacles_list'])) {
// $query .= ' INNER JOIN new_spectacle ns ON ns.idnew=n.idnew ';
// }
//
// $query .= ' WHERE 1 ';
//
// //recherche stricte par id
// if(!empty($idnew)) {
// $query .= ' AND n.idnew='.$idnew;
// }
// // mots cles
// if (!empty($keywords)) {
// $query .= ' AND n.title LIKE \'%'.$this->escape($keywords).'%\' ';
// }
// // ville
// if (!empty($city)) {
// $query .= ' AND n.city LIKE \'%'.$this->escape($city).'%\' ';
// }
//
//
// // recherche par person
// if(!empty($params['persons_list'])) {
// $query .= ' AND np.idperson IN ('.$params['persons_list'].') ';
// }
//
// // recherche par spectacle
// if(!empty($params['spectacles_list'])) {
// $query .= ' AND ns.idspectacle IN ('.$params['spectacles_list'].') ';
// }
//
// // recherche par extranetuser
// if(!empty($params['idextranetuser'])) {
// $query .= ' AND n.idextranetuser='.(int)$params['idextranetuser'];
// }
//
// // selectionne les fiches hors ligne et ou valide
// foreach(array('publish','valid','idregion','country') as $f) {
// if (isset($_REQUEST[$f]) && my_is_int($_REQUEST[$f]) && $_REQUEST[$f]<2) {
// $query .= ' AND n.'.$f.'='.(int)$_REQUEST[$f];
// }
// if (!empty($params[$f]) && my_is_int($params[$f])) {
// $query .= ' AND n.'.$f.'='.(int)$params[$f];
// }
// }
//
// $query .= ' GROUP BY n.idnew';
// on lance la recherche
return $query->getQuery();
}
// }}}
// {{{ setToArray()
/** Liste des à propos dans un tableau associatif
*
* Tableau associatif notamment utilisé pour lister les informations sur les à proposs
*
* @access public
* @param bool $spec recherche ou non
* @return array
* @see findData()
*/
public function setToArray($spec = true)
{
// recherche
if ($spec == true) {
$this->findData();
}
$values = array();
$color = null;
$nb = 0;
while ($this->fetch()) {
$values[$nb] = $this->getInfosNews(null, array('schedule_detail' => true));
$values[$nb]['id'] = $this->idnew;
$values[$nb]['nameview'] = $this->cutSentence($this->title, 150);
// couleur de ligne alternative
$color = $this->colorAlternate($color);
$values[$nb]['colorline'] = $color;
$nb++;
}
return $values;
}
// }}}
// {{{ getInfosNews()
/** Infos sur une actualite
*
* Retourne un tableau associatif avec les principales
* informations sur une annonce
*
* @access public
* @param int $idnew Identifiant de la fiche actualite
* @return array
* @see findData()
*/
public function getInfosNews($idnew = null, $params_data = array())
{
$infos = array();
$con = $this->getEntityManager();
////////////// infos de la table
if (!empty($idnew)) {
$data = $this->find($idnew);
if (empty($data)) {
return $data;
}
} else {
return false;
}
$infos += array(
'idnew' => $data->getIdNew(),
'title' => $data->getTitle(),
'description' => $data->getDescription(),
'markdown' => $data->getMarkdown(),
'url' => $data->getUrl(),
'type_news' => $data->getTypeNews(),
'url_more' => $data->getUrlMore(),
'url_file' => $data->getUrlFile(),
'idextranetuser' => $data->getIdextranetuser()->getIdextranetuser(),
'publish' => $data->getPublish(),
'valid' => $data->getValid(),
'statut' => $data->getStatut(),
'dateinsert' => $data->getDateInsert(),
'dateupdate' => $data->getDateUpdate()
);
$this->loadResult($infos);
// récupèrer le calendrier de la news
if (!empty($params_data['schedule_detail'])) {
$infos['schedule_detail'] = $con->getRepository(Newschedules::class)->getDateLieuCommon('tous', $infos['idnew'], null, 'ASC');
}
// date d'insertion
if (!empty($data->getDateInsert())) {
$infos['created'] = $this->getFormeDate($data->getDateInsert(), $GLOBALS['format_date_heure'][$GLOBALS['lng']]);
$infos['date_creation'] = $this->getFormeDate($data->getDateInsert(), '%d/%m/%y à %H:%m', true);
}
// date de modification
if (!empty($data->getDateupdate()) && $data->getDateupdate() != '0000-00-00 00:00:00') {
$infos['updated'] = $this->getFormeDate($data->getDateupdate(), $GLOBALS['format_date_heure'][$GLOBALS['lng']]);
$infos['date_modification'] = $this->getFormeDate($data->getDateupdate(), '%d/%m/%y à %H:%m', true);
}
// est-ce qu'il faut rechercher la prochaine date à partir d'une date donnée (datestart) ?
if (!empty($params_data['special']['depuis_le'])) {
$date_debut_recherche = $this->getFormeDate($params_data['special']['depuis_le']);
} else {
$date_debut_recherche = null;
}
// trouver la date et le lieu le plus proche
if (!empty($params_data['special']['anciens'])) {
$periode = array('anciens' => true);
} elseif (!empty($params_data['special']['plus_proche'])) { // la date la plus proche passée ou future
$periode = array('plus_proche' => true);
} elseif (!empty($params_data['special']['date_creation'])) {
} else { // la premiere date future
$periode = array('prochains' => true);
}
$infos['vignette'] = $this->getVignetteNew($infos['idnew']);
// definir un début de recherche
if ($date_debut_recherche) {
$periode['depuis_le'] = $date_debut_recherche;
}
//$periode['plus_proche'] = $date_debut_recherche;
// ajoute les infos sur les dates et lieux prochains
$infos['schedule'] = $this->getProchDateLieu($periode, $infos['idnew'], null);
if (empty($infos['schedule'])) {
$periode = array('plus_proche' => true);
$infos['schedule'] = $this->getProchDateLieu($periode, $infos['idnew'], null);
}
// insérer par l'administrateur ou par un autre user
if (empty($this->idextranetuser)) {
$infos['extranetuser']['login'] = 'Administrateur';
$infos['extranetuser']['is_admin'] = true;
} else {
$infos['extranetuser']['idextranetuser'] = $this->idextranetuser;
$extranetusers_fields = array(
'lastname',
'firstname',
'signature',
'login',
'city',
'enseignant_etablissement'
);
foreach ($extranetusers_fields as $f) {
if (isset($this->$f)) {
if ($f == 'city_extranetuser') {
$infos['extranetuser']['city'] = $this->$f;
} else {
$infos['extranetuser'][$f] = $this->$f;
}
}
}
}
// les contacts, les personnes et les spectacles liées
$infos['persons'] = $this->noPunct($this->getLinkedObject($this->getRelationsArray('new_person'), $this->idnew, 'new_person', 'news'));
$infos['contacts'] = $this->noPunct($this->getLinkedObject($this->getRelationsArray('new_contact'), $this->idnew, 'new_contact', 'news'));
$infos['spectacles'] = $this->noPunct($this->getLinkedObject($this->getRelationsArray('new_spectacle'), $this->idnew, 'new_spectacle', 'news'));
$infos['texts'] = $this->noPunct($this->getLinkedObject($this->getRelationsArray('new_text'), $this->idnew, 'new_text', 'news'));
/*$wiki->setOpt('active_quote', 1);
$wiki->setOpt('active_fix_word_entities',1);
$wiki->setOpt('active_fr_syntax',1);*/
$markdown = ($infos['markdown'] || !empty($params_data['markdown_force'])) ? true : false;
//conversion des champs (wiki, valeurs par défaut)
if (empty($params_data['no_wiki_convert'])) {
$keys_to_convert = array('description' => 200);
if (!empty($keys_to_convert)) {
foreach ($keys_to_convert as $f => $v) {
// texte court
$t = strip_tags($this->wikiTransform($this->$f, $this->markdown));
$infos[$f . '_cut'] = $this->cutSentence($t, $v);
// texte normal
$infos[$f] = $this->wikiTransform($this->$f, $markdown);
// ne pas afficher un autre texte si c'est la même taille
if (!empty($v) && (strlen($this->$f) == strlen($infos[$f . '_cut']))) {
$infos['no_long_text'] = true;
}
}
}
}
// infos sur l'actualite
return $infos;
}
// }}}
// {{{ orderByDefaut()
/** Classement par défaut
*
* Défini le tri par défaut pour les requêtes de type SELECT
*
* @access public
* @param string $order ordre
* @return string
*/
public function orderByDefaut($order = null)
{
// tri par défaut
if (empty($order)) {
$order = 'n.dateinsert';
}
return $order;
}
// }}}
// {{{ getInfosNewsRow()
/** Infos sur une actualite
*
* les principales
* informations sur une news dans une boucle
*
* @access public
* @param int $idnew Identifiant de la fiche actualite
* @return array
* @see findData()
*/
public function getInfosNewsRow($idnew = null, $params_data = array())
{
$infos = $this->getInfosNews($idnew, $params_data);
return $infos;
}
// }}}
// {{{ getLastNews()
/** récupérer les dernières news
*
* @access public
* @param int $idnew Identifiant de la fiche actualite
* @return array
* @see findData()
*/
public function getListNewsObject($object, $idobject, $limit, $periode = 'next', $date_suivante)
{
$obj = Theatre::factory('new_' . $object);
// on recup aussi le login de l'utilisateur
$sql_news = 'SELECT n.*,e.login,o.* FROM ' . $this->__table . ' n, extranetusers e, ' . $obj->__table . ' o
WHERE e.idextranetuser=n.idextranetuser
AND o.' . $this->__idtable . '=n.' . $this->__idtable . '
AND o.id' . $object . '=' . ((int)$idobject) . '
AND n.publish=1 AND n.valid=1 ';
// limite dans le future
if ($periode == 'next') {
$sql_news .= ' AND n.date_start>=\'' . date('Y-m-d') . '\' ';
}
$sql_news .= ' ORDER BY n.date_start LIMIT 0,' . (int)$limit;
$this->query($sql_news);
$news = array();
// mise en forme des donnees
while ($this->fetch()) {
$news[] = $this->getInfosNewsRow();
}
return $news;
}
// }}}
// {{{ getRelationsArray()
/** Tableau des relations
*
* @access public
* @param string|int $type le type de champ
*/
public function getRelationsArray($type = null)
{
$array_types = array(
// extranetusers idextranetuser
'idextranetuser' => array(
'type_join' => 'simple',
'dest_table' => 'extranetusers',
'join_field_src' => 'idextranetuser',
'fields' => array('idextranetuser', 'lastname', 'firstname', 'login'),
'description' => 'Utilisateur(s) associé(s) à cet évènement',
'silent_delete_relation' => true,
),
// new_person idnew
'new_person' => array(
'type_join' => 'multiple',
'dest_table' => 'persons',
'join_table' => 'new_person',
'fields' => array('idperson', 'lastname', 'firstname', 'url_clean', 'valid'),
'description' => 'Personne(s) associée(s) à cet évènement',
'silent_delete_relation' => true,
),
// new_contact idnew
'new_contact' => array(
'type_join' => 'multiple',
'dest_table' => 'contacts',
'join_table' => 'new_contact',
'fields' => array('idcontact', 'lastname', 'firstname', 'organisation', 'type', 'url_clean'),
'description' => 'Contact(s) associé(s) à cet évènement',
'silent_delete_relation' => true,
),
// new_spectacle idnew
'new_spectacle' => array(
'type_join' => 'multiple',
'dest_table' => 'spectacles',
'join_table' => 'new_spectacle',
'fields' => array('idspectacle', 'title', 'valid', 'publish', 'url_clean'),
'description' => 'Spectacle(s) associé(s) à cet évènement',
'silent_delete_relation' => true,
),
// new_text idnew
'new_text' => array(
'type_join' => 'multiple',
'dest_table' => 'texts',
'join_table' => 'new_text',
'fields' => array('idtext', 'title', 'valid', 'publish', 'url_clean'),
'description' => 'texte(s) associé(s) à cet évènement',
'silent_delete_relation' => true,
),
);
if (!empty($array_types[$type])) {
$array_types[$type]['type'] = $type;
return $array_types[$type];
} else {
return $array_types;
}
}
// }}}
// {{{ getObjectTitle()
/** Infos de l'item recherché
*
*
* @access public
* @param int $idobject Identifiant de l'item
* @param array $infos_object Informations pour construire le titre
* @param array $params Paramétres supplémentaires
* @return string|array
*/
public function getObjectTitle($idobject = null, $infos_object = array(), $params = array())
{
if (!$idobject && isset($this->idperson)) $idobject = $this->idperson;
// champs
$fields = array('idnew', 'title');
if (!empty($infos_object)) {
foreach ($fields as $k => $v) {
if (array_key_exists($v, $infos_object)) {
$infos[$v] = $infos_object[$v];
} else {
$infos[$v] = '';
}
}
} else {
//charger les infos que si necessaire
if (empty($this->title)) {
$sql = 'SELECT ' . implode(',', $fields) . '
FROM ' . $this->__table . '
WHERE ' . $this->__idtable . '=' . $idobject;
$infos = $this->queryRow($sql);
} else {
foreach ($fields as $k => $v) {
if (isset($this->$v) && $this->$v != '') {
$infos[$v] = trim($this->$v);
} else {
$infos[$v] = '';
}
}
}
}
// renvoyer un array plutôt que le titre (utile si on veux l'url)
if (array_key_exists('return_array', $params)) {
return $infos;
}
return $infos['title'];
}
// }}}
// {{{ getSQLNews()
/** Générer la requete standard pour les news
*
* $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)
* )
* $special = array(
* 'prochains' => true = date dans le future, un entier = fait un between
* 'anciens' =>
* 'join' => jointure gauche sur contacts et schedules
* )
*
*
* @access public
* @param array $params Les paramètres pour la requete
* @param array $special Les paramètres supplémentaires
* @param bool $debug afficher la requête TODO
* @return string
*/
public function getSQLNews($params = array(), $special = array(), $debug = false)
{
$conn = $this->getEntityManager();
// tables et champs
$tables_list = array(
'news' => array(
'fields' => array('*'),
),
'extranetusers' => array(
'fields' => array('idextranetuser', 'lastname', 'firstname', 'signature', 'city as city_extranetuser', 'enseignant_etablissement', 'enseignant_active'),
),
'newschedules' => array(
'fields' => array('idnewschedule', 'date', 'hour', 'idcontact', 'note'),
),
);
// définition de l'alias
$al = 1;
foreach ($tables_list as $k => $v) {
$tables_list[$k]['table_alias'] = $k . ' T' . $al;
foreach ($v['fields'] as $f) {
$select_fields_array[] = 'T' . $al . '.' . $f;
}
$al++;
}
// select de base
$sql_select = 'SELECT DISTINCT(T1.' . $this->__idtable . '), ' . join(',', $select_fields_array) . ' ';
// select en plus sous forme de string
if (array_key_exists('select', $params)) {
$sql_select .= ',' . $params['select'];
}
// compte seulement les résulats
if (array_key_exists('count_only', $special)) {
$sql_select = 'SELECT COUNT(DISTINCT(T1.' . $this->__idtable . ')) as total ';
}
// from avec jointure entre news et extranetusers
if (!array_key_exists('no_join', $special)) {
$sql_from = ' FROM ' . $this->__table . ' T1 ';
// seulement avec calendrier ?
if (array_key_exists('no_schedule', $special)) {
$join_direction = 'LEFT';
} else {
$join_direction = 'INNER';
}
// seulement avec calendrier et contact ?
if (array_key_exists('no_schedule_contact', $special)) {
$join_direction_contact = 'INNER';
} else {
$join_direction_contact = 'LEFT';
}
$sql_from .= $join_direction . ' JOIN newschedules T3
ON T3.idnew=T1.idnew
INNER JOIN extranetusers T2 ON T2.idextranetuser=T1.idextranetuser
' . $join_direction_contact . ' JOIN contacts T4 ON T4.idcontact=T3.idcontact ';
} else {
foreach ($tables_list as $k => $v) {
$sql_from_tables[] = $v['table_alias'];
}
$sql_from = ' FROM ' . join(',', $sql_from_tables);
}
// jointure sur un objet => faire un foreach pour gérer plusieurs contraintes => liaison dans cet object OU avec cet object (cas du calendrier)
if (array_key_exists('by_object', $special)) {
$alias_bo = 'T' . ($al + 1);
foreach ($special['by_object'] as $k => $v) {
$object_by = str_replace('id', '', $k);
$sql_from .= ' LEFT JOIN new_' . $object_by . ' ' . $alias_bo . ' ON ' . $alias_bo . '.' . $this->__idtable . '=T1.' . $this->__idtable . ' ';
}
}
// selection de table en plus sius forme de string
if (array_key_exists('from', $params)) {
$sql_from .= ',' . $params['from'];
}
// where standard
$sql_where = ' WHERE 1 ';
// recherche par objet
if (array_key_exists('by_object', $special)) {
foreach ($special['by_object'] as $k => $v) {
$sql_where .= ' AND (' . $alias_bo . '.' . $k . '=' . (int)$v . ' )';
//$sql_where .= ' OR T3.idcontact='.$v.')';
//$sql_where .= ''
}
}
// paramètres where en plus sous forme de string
if (array_key_exists('where', $params)) {
$sql_where .= $params['where'];
}
// publie ou pas ?
if (!array_key_exists('publish', $special)) {
$sql_where .= ' AND T1.publish=1';
} else {
if ($this->my_is_int($special['publish'])) {
$sql_where .= ' AND T1.publish=' . (int)$special['publish'];
}
}
if (array_key_exists('is_homepage', $special)) {
$sql_where .= ' AND T1.`is_homepage`=' . (int)$special['is_homepage'];
}
// valid et publié uniquement
if (array_key_exists('publish_valid', $special)) {
$sql_where .= ' AND T1.publish=1 AND T1.valid=1 ';
}
// type de news ? (spectacle ou évènement)
if (array_key_exists('type_news', $special)) {
if ($this->my_is_int($special['type_news'])) {
$sql_where .= ' AND T1.type_news=' . $special['type_news'] . ' ';
} else {
// 2 types de news
$types_news = array(
'news' => 0,
'spectacles' => 1
);
// on checke
if (array_key_exists($special['type_news'], $types_news)) {
$sql_where .= ' AND T1.type_news=' . $types_news[$special['type_news']];
}
}
}
// par un utuilisateur
if (array_key_exists('idextranetuser', $special)) {
if (is_array($special['idextranetuser'])) {
$sql_where .= ' AND T1.idextranetuser IN (' . join(',', $special['idextranetuser']) . ') ';
} else {
$sql_where .= ' AND T1.idextranetuser=' . (int)$special['idextranetuser'] . ' ';
}
}
// dans une structure
if (array_key_exists('idtypestructure', $special)) {
$sql_where .= ' AND T4.idtypestructure=\'' . $special['idtypestructure'] . '\' ';
}
// dans une grande région
if (array_key_exists('idbigregion', $special)) {
if (is_array($special['idbigregion'])) {
$bigregions = $conn->getRepository(Bigregions::class);
$sql_region = $bigregions->getZipCode(end($special['idbigregion']), 'T4');
} else {
$bigregions = $conn->getRepository(Bigregions::class);
$sql_region = $bigregions->getZipCode($special['idbigregion'], 'T4');
}
$sql_where_and[] = str_replace(' AND T4.country', 'T4.country', $sql_region);
}
// dans un pays
if (array_key_exists('country', $special)) {
foreach ($special['country'] as $c) {
$country_tabs[] = '\'' . $c . '\'';
}
$sql_where_and[] = ' T4.country IN (' . join(',', $country_tabs) . ') ';
}
// prochains uniquement => date comprise entre le début et la fin
if (array_key_exists('prochains', $special)) {
// convertir à date du jour + le params
$sql_where_and[] = ' T3.date>=\'' . date('Y-m-d') . '\' ';
}
// anciens
if (array_key_exists('anciens', $special)) {
// évènements terminé
$sql_where_and[] = ' T3.date<\'' . date('Y-m-d') . '\' ';
}
// nouveau code
if (!empty($sql_where_and)) {
$sql_where_lieu_date[] = '(' . join(' AND ', $sql_where_and) . ')';
}
$old_code = false;
if ($old_code) {
// dans une région
if (array_key_exists('idregion', $special)) {
$sql_where_old[] = 'T1.idregion IN (' . join(',', $special['idregion']) . ') ';
}
// dans un pays
if (array_key_exists('country', $special)) {
foreach ($special['country'] as $c) {
$country_tabs[] = '\'' . $c . '\'';
}
$sql_where_old[] = 'T1.country IN (' . join(',', $country_tabs) . ') ';
}
// prochains uniquement => date comprise entre le début et la fin
if (array_key_exists('prochains', $special)) {
if ($this->my_is_int($special['prochains'])) {
// convertir à date du jour + le params
$sql_where_old[] = 'T1.date_start>NOW() ';
} else {
// évènements commencé mais non terminé
$sql_where_old_date = '(';
$sql_where_old_date .= ' (date_start<=NOW() AND (date_end IS NOT NULL AND date_end>=NOW()) ) ';
$sql_where_old_date .= ' OR ';
//évènement qui vont commencer
$sql_where_old_date .= ' (date_start>=\'' . date('Y-m-d') . '\') ';
$sql_where_old_date .= ') ';
$sql_where_old[] = $sql_where_old_date;
}
}
// anciens
if (array_key_exists('anciens', $special)) {
// évènements terminé
$sql_where_old_date = '(';
$sql_where_old_date .= ' (date_start<NOW() AND (date_end IS NOT NULL AND date_end<NOW()) ) ';
$sql_where_old_date .= ' OR ';
//évènement qui vont commencer
$sql_where_old_date .= ' (date_start<NOW()) ';
$sql_where_old_date .= ') ';
$sql_where_old[] = $sql_where_old_date;
}
// ancien code
if (!empty($sql_where_old)) {
$sql_where_lieu_date[] = '(' . join(' AND ', $sql_where_old) . ')';
}
} // fin ancien code
if (!empty($sql_where_lieu_date)) $sql_where .= ' AND (' . join(' OR ', $sql_where_lieu_date) . ') ';
$order = ' ';
$groupby = ' ';
$limit = ' ';
if (!array_key_exists('count_only', $special)) {
// groupement par défaut
if (!array_key_exists('groupby', $params)) {
$groupby = ' GROUP BY T1.' . $this->__idtable . ' ';
} else {
$groupby = ' GROUP BY ' . $params['groupby'];
}
// classement par défaut
if (!array_key_exists('order', $params)) {
// si ancien, classement DESC
if (array_key_exists('anciens', $special)) {
$classement = 'DESC';
} else {
$classement = 'ASC';
}
if (array_key_exists('classement', $params)) {
$classement = $params['classement'];
}
if (!empty($sql_where_old)) {
$order = ' ORDER BY T3.date, T1.date_start ' . $classement;
} else {
$order = ' ORDER BY T3.date ' . $classement;
}
} else {
$order = ' ORDER BY ' . $params['order'];
}
}
// classement aléatoire
if (array_key_exists('random', $special)) {
$order = ' ORDER BY RAND() ' . $special['random'];
}
// limite par défaut
if (!array_key_exists('limit', $params)) {
$limit = ' LIMIT 0,10';
} else {
if ($params['limit'] != 'all') {
$limit = ' LIMIT ' . $params['limit'][0] . ',' . $params['limit'][1];
} else {
$limit = ' ';
}
}
// compte le tout
if (array_key_exists('count_only', $special) && $special['count_only'] == 'all') {
$limit = ' ';
}
// random sur les résultats ?
$sql_global = $sql_select . $sql_from . $sql_where . $groupby . $order . $limit;
return $sql_select . $sql_from . $sql_where . $groupby . $order . $limit;
}
// }}}
// {{{ getListNews()
/** Récupére la liste des news
*
* Récupére les news de manière standard
*
* @access public
* @param array $params_sql paramètre pour la requete SQL
* @param array $format de la vignette si pas standard
* @param bool $debug mode débugage
* @return array
*/
public function getListNews($params_sql = array(), $params = array(), $debug = false)
{
// si pas de tableau
if (!isset($params_sql['special'])) {
$params_sql['special'] = array();
}
if (!isset($params_sql['params'])) {
$params_sql['params'] = array();
}
if (!empty($params['display'])) {
$display = $params['display'];
unset($params['display']);
} else {
$display = array();
}
// pagination ?
if (!empty($params_sql['special']['pagerOptionsFromController'])) {
$limit = $params_sql['special']['pagerOptionsFromController']['limit'];
$perPage = $params_sql['special']['pagerOptionsFromController']['perPage'];
$params_sql['params']['limit'] = array($limit, $perPage);
}
// construction de la requête avec le passage de paramètres
$sql = $this->getSQLNews($params_sql['params'], $params_sql['special'], $debug);
// paramètre de debug
$dbg = (empty($params_sql['dbg'])) ? array() : $dbg = $params_sql['dbg'];
// executer la requete
$datas = $this->query($sql, $dbg);
$nws = array();
$params_row = array();
// format de la vignette
if (!empty($params['vignette_format'])) {
$vignette_format = $params['vignette_format'];
} else {
$vignette_format = array('width' => 100, 'height' => 70, 'direction' => 'thumb');
}
// debug
$start_boucle = microtime(true);
// mettre en forme chaque reponse
$conn = $this->getEntityManager();
$x = $conn->getRepository(News::class);
foreach ($datas as $data) {
$this->loadResult($data);
$y = $this->getInfosNewsRow($this->{$this->__idtable}, $params_sql);
$idnew = $y['idnew'];
// il faut classer par type
if (!empty($params['par_type'])) {
if ($this->type_news == 0) {
$nws['news'][$idnew] = $y;
} else {
$nws['spectacles'][$idnew] = $y;
}
} else {
$nws[$idnew] = $y;
}
$nws[$idnew]['display'] = $display;
}
// libère
$this->free();
// debug de la boucle
if ($this->isTraceMode('list_object')) {
$this->setTraceInfos(array(
'execution_time_boucle' => (microtime(true) - $start_boucle),
'dbg' => $dbg,
));
}
return $nws;
}
// }}}
// {{{ countNews()
/** compter le nombre de news
*
* @access public
* @param array $params paramètre (exemple : by_object => idperson)
* @return int
*/
public function countNews($news_params = array())
{
$news_params['special']['count_only'] = true;
if (empty($news_params['sql'])) {
$news_params['sql'] = array();
}
$sql = $this->getSQLNews($news_params['sql'], $news_params['special']);
$nb_news = $this->queryOne($sql);
if ($nb_news) {
return $nb_news;
} else {
return null;
}
}
// }}}
// {{{ getTypeNew()
/** Les types de news
*
* @access public
* @return array
*/
public function getTypesNews($type_news = null)
{
$types_news = array(
0 => 'news',
1 => 'spectacles',
);
return $types_news;
}
//
// {{{ getVignetteNew()
/** Récupère la vignette d'une news ou la cree si besoin
*
* @access public
* @param int idspectacle identifiant du spectacle
* @param array format $format de la vignette
* @return string
*/
public function getVignetteNew($idnew = null, $format = array(), $url_file = null)
{
// id de la new
if (empty($idnew)) {
$idnew = $this->idnew;
}
$idnew = (int)$idnew;
// par default : image arrondie crop 100px x 100px qualite 75
if (!empty($format)) {
$set_format = $format;
} else {
$set_format = array('width' => 80, 'height' => 80, 'direction' => 'crop', 'forme' => 'round', 'valround' => 100, 'default' => '../../default/news-def.png');
}
// generation par la classe Images
if (!empty($url_file)) {
$url_file = $_ENV['PATH_DIRECTORYUPLOAD'] . 'news/src/' . $this->images->getHashDir($url_file, true) . $url_file;
} else {
$sql = 'SELECT url_file FROM ' . $this->__table . ' WHERE idnew=' . (int)$idnew;
$url_file = $this->queryOne($sql);
// if(empty($url_file) || is_null($url_file)) {
// $url_file = null;
// } else {
$url_file = $_ENV['PATH_DIRECTORYUPLOAD'] . 'news/src/' . $this->images->getHashDir($url_file, true) . $url_file;
// }
}
$this->images->setVignetteFormat($set_format);
return $this->images->getVignetteObject($idnew, 'news', 'unknow_classification', $url_file);
}
// }}}
// {{{ delete()
/** Supprimer une news et ses images
*
* @access public
* @param int idnew identifiant du new
* @param array format $format de la vignette
* @return string
*/
public function deleteData($idnew = null, $url_file = null)
{
$conn = $this->getEntityManager();
// si on a l'URL du fichier, on peux le supprimer ainsi que ses vignettes
if (empty($url_file)) {
$sql = 'SELECT url_file FROM ' . $this->__table . ' WHERE idnew=' . (int)$idnew;
$url_file = $this->queryOne($sql);
}
if (!empty($url_file)) {
// classe des images
$url_file_src = $_ENV['PATH_DIRECTORYUPLOAD'] . 'news/src/' . $this->images->getHashDir($url_file, true) . $url_file;
// supprimer les vignettes
$files = $conn->getRepository(Files::class);
$files->deleteVignettes(null, 'news', $idnew, array('file' => $url_file));
// supprimer le fichier
if (file_exists($url_file_src)) {
@unlink($url_file_src);
}
}
// supprimer la news
$this->deleteDataTrait($idnew);
return true;
}
// }}}
// {{{ getProchDateLieu()
/** Lieu et date d'une news
*
* Pour une news, la prochaine date et ville pour (au choix) :
* - un contact donné
* - une date passée ou future
* - une zone géographique donnée
*
* @access public
* @param string $periode futur ou passé ?
* @param int $idnew identifiant de la news
* @param int $idcontact date spécifiquement dans un lieu ?
* @param int $zone date spécifiquement dans une zone géographique ?
* @return array
*/
public function getProchDateLieu($periode = 'prochains', $idnew, $idcontact = null, $zone = null, $special_schedule = null)
{
// trouver la date et le lieu le plus proche dans le futur ou le passé
if (isset($this->lastdate) || array_key_exists('anciens', $periode)) {
$eq = '<';
$tri = 'DESC';
} elseif (array_key_exists('plus_proche', $periode)) { // la premiere date future
$tri = 'ASC';
if ($periode['plus_proche'] == 'all') {
$eq = '>=';
}
} else {
$eq = '>=';
$tri = 'ASC';
}
// voir si on doit partir d'une date précise pour la recherche de la date la plus proche dans le futur ou le passé
if (array_key_exists('depuis_le', $periode)) {
$date_debut_recherche = $periode['depuis_le'];
} else {
$date_debut_recherche = date('Y-m-d');
}
// on veux exclure un contact en créeant une table temporaire
if ($special_schedule) {
$from_schedules = '(SELECT idcontact,idnew,date
FROM newschedules
WHERE idnew=' . ((int)$idnew) . '
AND idcontact !=' . $idcontact . '
AND date' . $eq . '\'' . $date_debut_recherche . '\') AS';
} else {
$from_schedules = 'newschedules';
}
// le select pour trouver la première date future
$select_prochdate = 'sc.date, c.city, c.country, c.zip, c.organisation, c.url_clean, c.idcontact';
// le select pour trouver la periode
$select_periode = 'MIN(sc.date) as datestart, MAX(sc.date) as dateend, c.city, c.country';
// le from commun pour prochaine date et periode
$from_commun = ' FROM ' . $from_schedules . ' sc, contacts c
WHERE sc.idcontact=c.idcontact
AND sc.idnew=' . ((int)$idnew);
// recherche de la date la plus proche passé ou future
$sql_prochdate = 'SELECT ' . $select_prochdate . $from_commun;
// init
$sql_more = null;
if ($from_schedules == 'newschedules' && !empty($eq)) {
$sql_more .= ' AND sc.date' . $eq . '\'' . $date_debut_recherche . '\' ';
}
// uniquement dans un lieu
if ($idcontact) {
if (is_array($idcontact)) {
$sql_more .= ' AND c.idcontact IN (' . join(',', $idcontact) . ')';
} else {
$sql_more .= ' AND c.idcontact=' . ((int)$idcontact);
}
}
// sur une zone geographique précise
if (isset($this->zone_recherche['zip'])) {
$sql_more .= $this->zone_recherche['zip'];
}
// on tri par date et on ne prends que le premier pour le début de la période
$sql_prochdate_limit = ' ORDER BY sc.date ' . $tri . ' LIMIT 0,1';
$sql_prochdate_construct = $sql_prochdate . $sql_more . $sql_prochdate_limit;
$prochdate = $this->queryRow($sql_prochdate_construct);
// si il n'y a pas de prochaine date, rechercher la précédente
if (empty($prochdate['date']) && array_key_exists('plus_proche', $periode)) {
$sql_prochdate_construct = str_replace('>=', '<=', $sql_prochdate_construct);
$sql_more = str_replace('>=', '<=', $sql_more);
$prochdate = $this->queryRow($sql_prochdate_construct);
}
if (!empty($prochdate['date'])) {
// recherche la suite de la période dans ce lieu (date début et date de fin dans le lieu)
$sql_periode = 'SELECT ' . $select_periode . $from_commun;
//$sql_periode_construct = $sql_periode.$sql_more.' GROUP BY c.idcontact';
$sql_periode_construct = $sql_periode . $sql_more . ' AND sc.idcontact=' . $prochdate['idcontact'] . ' GROUP BY sc.idcontact';
$prochedate_periode = $this->queryAll($sql_periode_construct);
$prochedate_periode = $prochedate_periode[0];
// debut et fin de la période en timestamp
$prochedate_periode['datestart_std'] = $prochedate_periode['datestart'];
$prochedate_periode['dateend_std'] = $prochedate_periode['dateend'];
// début et fin de la période en français
$prochedate_periode['datestart'] = $this->getFormeDate($prochedate_periode['datestart'], "%a %d/%m/%y", true);
$prochedate_periode['dateend'] = $this->getFormeDate($prochedate_periode['dateend'], "%a %d/%m/%y", true);
// si date start est égale a dateend, alors on a qu'une date
if ($prochedate_periode['datestart_std'] == $prochedate_periode['dateend_std']) {
$prochedate_periode['datestart'] = null;
}
if (empty($prochedate_periode['datestart'])) {
$spec['prochdate'] = $prochedate_periode['dateend'];
} else {
$spec['periode'] = $prochedate_periode;
$spec['prochdate'] = null;
}
// la ville et le pays de la prochaine date ou de la période
$spec['city'] = $prochedate_periode['city'];
$spec['country'] = $prochedate_periode['country'];
// date standard
$spec['date_std'] = $prochdate['date'];
// infos sur le contact
if (!empty($prochdate['organisation'])) {
$spec['contact'] = array(
'organisation' => $prochdate['organisation'],
'idcontact' => $prochdate['idcontact'],
'url_clean' => $prochdate['url_clean']
);
}
return $spec;
}
return array();
}
// }}}
// {{{ setZoneRecherche()
/** Zone de recherche d'un new
*
* @access public
* @param array $zone Zone de recherche
*/
public function setZoneRecherche($zone)
{
$this->zone_recherche['zip'] = $zone;
}
// }}}
}