<?php
namespace TheatreCore\Repository;
use TheatreCore\Classes\Images\Images;
use TheatreCore\Entity\Aides;
use TheatreCore\Entity\Contents;
use TheatreCore\Entity\TextAide;
use TheatreCore\Entity\Texts;
use TheatreCore\Traits\TheatreTrait;
use DateTime;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
use Doctrine\ORM\Query;
use Symfony\Contracts\Translation\TranslatorInterface;
/**
* TextsRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class TextsRepository extends ServiceEntityRepository
{
use TheatreTrait {
getLinkedObject as protected getLinkedObjectTrait;
}
private $em;
public $__table;
public $__table_object;
public $__idtable;
public function __construct(ManagerRegistry $registry, TranslatorInterface $tr, Images $images)
{
parent::__construct($registry, Texts::class);
$this->__table = $this->getClassMetadata()->getTableName();
$this->__table_object = $this->getClassMetadata()->name;
$this->__idtable = $this->getClassMetadata()->getSingleIdentifierFieldName();
$this->translator = $tr;
$this->images = $images;
}
// {{{ findData()
/** Recherche des texts
*
* Permet de rechercher des textes en fonction de certains critères :
* la première lettre, un bout du titre, le type de texte, si il est en ligne ou pas
*
* @access public
* @see Theatre::find()
*/
public function findData($idtext = null, $idperson = null, $typetxt = null, $keywords = null, $lettre = null)
{
// query perso
$query = null;
$query = $this->createQueryBuilder('e');
// l'id du texte
if (isset($_REQUEST['idtext']) && (int)$_REQUEST['idtext']) {
$idtext = $_REQUEST['idtext'];
}
// l'id d'un auteur
if (isset($_REQUEST['idperson']) && (int)$_REQUEST['idperson']) {
$idperson = $_REQUEST['idperson'];
}
// premiere lettre du titre
if (isset($_REQUEST['lettre']) && !empty($_REQUEST['idperson'])) {
$lettre = $_REQUEST['lettre'];
}
// type de texte
if (isset($_REQUEST['typetxt']) && !empty($_REQUEST['typetxt'])) {
$typetxt = $_REQUEST['typetxt'];
}
// // mots cles
if (isset($_REQUEST['keywords']) && $_REQUEST['keywords'] != 'titre' && !empty($_REQUEST['keywords'])) {
$keywords = filter_var(trim($_REQUEST['keywords']), FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES);
if ($this->my_is_int($keywords)) {
$idtext = (int)$keywords;
$keywords = null;
}
}
// liste des traductions
if (isset($_REQUEST['listtraductions']) && $_REQUEST['listtraductions'] == true) {
$listtraductions = true;
}
// publie ou pas
if (isset($_REQUEST['publish']) && !empty($_REQUEST['publish'])) {
$publish = $_REQUEST['publish'];
} else {
$publish = null;
}
// fictif ou pas
if (isset($_REQUEST['textfictif']) && !empty($_REQUEST['textfictif'])) {
$textfictif = (int)$_REQUEST['textfictif'];
} else {
$textfictif = 0;
}
// aides
if (isset($_REQUEST['idaide']) && $this->my_is_int($_REQUEST['idaide'])) {
$idaide = (int)$_REQUEST['idaide'];
}
$lng = 'fr'; //$GLOBALS['lng'];
$query_select = 'partial e.{title, date, type, idtext, publish, valid, statut, country, language, textfictif}';
$join_on = ',ct.' . $lng . ' as country_str,ln.' . $lng . ' as language_str';
// // on precise les champs pour le SELECT
if (empty($idperson)) {
//// $this->selectAdd();
// $this->selectAdd('title,date,type,idtext,publish,valid,country,language,textfictif');
$query->leftJoin('e.text_author', 'authors');
// $query->select('e, authors');
$query->select($query_select);
}
// // recherche par ID
if (!empty($idtext)) {
$query->andWhere('e.idtext=' . $idtext);
// $query .= ' AND t.idtext='.$idtext;
}
// // recherche par alphabet
if (!empty($lettre)) {
$query->andWhere('title REGEXP \'^' . $this->escape($lettre) . '\' ');
//// $query .= ' AND t.title REGEXP \'^'.$this->escape($lettre).'\' ';
}
// // recherche par mots cles
if (!empty($keywords)) {
// $this->whereAdd('title LIKE \'%'.$this->escape($keywords).'%\'');
// $query .= ' AND t.title LIKE \'%'.$this->escape($keywords).'%\'';
}
// // selectionne uniquement les textes originaux
if ($typetxt == 'original') {
// $this->whereAdd('type=0');
// $query .= ' AND t.type=0';
}
// // selectionne uniquement les traductions
if ($typetxt == 'translate') {
$query->andWhere('e.type = 1');
// $query .= ' AND t.type=1';
}
// // selectionne uniquement les adaptations
if ($typetxt == 'adaptation') {
$query->andWhere('e.type=2');
// $query .= ' AND t.type=2';
}
// // selectionne les textes/traductions/adaptations en cours de rédaction
if (!empty($publish)) {
$query->andWhere('e.publish=0');
// $query .= ' AND t.publish=0';
}
//
// // selectionne les textes fictifs
// $this->whereAdd('textfictif='.$textfictif);
// $query .= ' AND t.textfictif='.$textfictif;
//
// // selectionne uniquement les textes publies
if (!empty($this->isPublish) || (isset($GLOBALS['publish']) && $GLOBALS['publish'] == 1)) {
$query->andWhere('publish=1');
$query .= ' AND t.publish=1';
}
// // recherche par auteur ou traducteur
if (!empty($idperson)) {
// // jointure pour recherche par auteurs
if ($typetxt == 'original') {
$ta = DB_DataObject::factory('textAuthor');
$this->joinAdd($ta);
$this->selectAs();
$this->selectAs($ta, 'ta_%s');
$this->whereAdd('text_author.idperson=' . $idperson);
}
// jointures pour recherche par traducteurs
if ($typetxt == 'translate') {
$tt = DB_DataObject::factory('textTranslator');
$this->joinAdd($tt);
$this->selectAs($tt, 'tt_%s');
$this->whereAdd('text_translator.idtext=' . $idperson);
}
}
//
// $query = 'SELECT '.$query_select.' FROM texts t, countries ct, languages ln
// WHERE 1
// AND ct.id=t.country
// AND ln.id=t.language '.$query;
//
// $query = null;
//
// // selectionne les traductions d'un texte
// if(!empty($idtext) && isset($listtraductions)) {
// $query = 'SELECT t.title,t.date,t.type,t.idtext,t.publish,t.valid,t.country,t.language,t.textfictif
// FROM texts t, text_traduction tt
// WHERE t.idtext=tt.idtexttraduction
// AND tt.idtext='.$idtext;
// }
//
// // les texts avec une aide
// if(!empty($idaide)) {
// $query = 'SELECT '.$query_select.',ta.*
// FROM texts t, text_aide ta
// WHERE t.idtext=ta.idtext
// AND ta.idaide='.$idaide;
// }
if ($this->getCount()) {
$query->select('COUNT(e.idtext)');
$this->setCount(false);
return $query;
}
// on lance la recherche
return $query->getQuery();
}
// }}}
// {{{ setToArray()
/** Listes des textes dans un tableau associatif
*
* Tableau associatif notament utilisé pour lister les informations sur des textes
* Utile pour gnérer les tableaux HTML de listes de textes
*
* @access public
* @return array
* @see findData()
*/
public function setToArray($spec = true)
{
if ($spec == true) {
$this->findData();
}
$values = array();
$color = null;
$nb = 0;
while ($this->fetch()) {
$this->getLinks();
$values[$nb] = $this->getInfosText();
$values[$nb]['id'] = $this->idtext;
$values[$nb]['valid'] = $this->valid;
$values[$nb]['statut'] = $this->statut;
// compter les traductions
if (isset($this->count_translations)) {
$values[$nb]['translations_nb'] = $this->countTranslations($this->idtext);
}
// couleur de ligne alternative
$color = $this->colorAlternate($color);
$values[$nb]['colorline'] = $color;
$nb++;
}
return $values;
}
// }}}
// {{{ getInfosText()
/** Infos sur un texte
*
* Retourne un tableau associatif avec les principales
* informations sur un texte
*
* @access public
* @param int $idtext Identifiant de la fiche texte
* @return array
* @see findData()
*/
public function getInfosText($idtext = null, $params_data = array())
{
$conn = $this->getEntityManager();
// infos de la table
if (!isset($this->idtext) || empty($this->idtext) || $this->idtext != $idtext) {
$this->idtext = $idtext;
}
$query = $this->createQueryBuilder('u')
->select('u, idextranetuser, country, idcontact_publisher, idgenretext')
->leftJoin('u.idextranetuser', 'idextranetuser')
->leftJoin('u.idcontact_publisher', 'idcontact_publisher')
->leftJoin('u.idgenretext', 'idgenretext')
->leftJoin('u.idcontact_performing', 'idcontact_performing')
->leftJoin('u.country', 'country')
->where('u.idtext =:value')->setParameter('value', $this->idtext);
$this->datas = $infos = $query->getQuery()->getOneOrNullResult(Query::HYDRATE_ARRAY);
$infos['titleshort'] = $this->cutSentence($infos['title'], 40);
$infos['year'] = $infos['date'];
$infos['special_text'] = $infos['specialText'];
$infos['idgenretext_object'] = $infos['idgenretext'];
if (!empty($infos['idgenretext'])) {
$infos['idgenretext'] = $infos['idgenretext']['idgenretext'];
}
$infos['publisher_url_text'] = $infos['publisherUrlText'];
$infos['url_clean'] = $infos['urlClean'];
$infos['abstract_url'] = $infos['abstractUrl'];
$infos['abstract_author'] = $infos['abstractAuthor'];
if (isset($this->_country->fr)) {
$infos['country'] = $this->_country->fr;
} elseif (isset($this->country_str)) {
$infos['country'] = $this->country_str;
} else {
if (isset($infos['country']['id'])) {
$infos['country'] = $infos['country']['id'];
}
}
$infos['country_src'] = $infos['language'];
$infos['language_src'] = $infos['language'];
$this->idtext = $idtext_original = $infos['idtext'];
switch ($infos['type']) {
/* Texte original */
case 0:
$infos['typetxt'] = 'original';
$infos['original'] = true;
break;
/* Traduction */
case 1:
$infos['typetxt'] = 'translate';
$infos['translate'] = true;
/* on veut l'auteur du texte original, pas de la traduction */
$originalText = $this->getOriginalsTexts($this->idtext);
// on renvoi l'id de l'original
$idtext_original = key($originalText);
$infos['idtextoriginal'] = $idtext_original;
/* traducteurs */
$infos['translators'] = $this->getTranslators($this->idtext);
$infos['alltranslators'] = $this->noPunct($infos['translators']);
// au dela de 1 traducteur, on dit que c'est un collectif
$this->collectif($infos['translators'], 1);
break;
/* Adaptation */
case 2:
$infos['typetxt'] = 'adaptation';
$infos['adaptation'] = true;
// on recup les infos sur l'adaptation
$infos['adaptation_infos'] = $this->getOriginalsTexts($this->idtext, 'text_adaptation', 'idtextadaptation');
break;
default:
error_log('Type de texte inconnu: ' . $infos['type']);
break;
}
// auteurs
$infos['authors'] = $this->getPersons($idtext_original, 'text_author');
// tous les auteurs
$infos['allauthors'] = $this->noPunct($infos['authors']);
// au dela de 1 auteur, on dit que c'est un collectif
$this->collectif($infos['authors'], 2);
// voir si il y a des aides
if (!empty($params_data['get_aides'])) {
$infos['nb_aides'] = $conn->getRepository(TextAide::class)->countAides(null, $this->idtext);
if ($infos['nb_aides'] > 0) {
$infos['aides'] = $conn->getRepository(TextAide::class)->getListTextAide(array(
'idtext' => array($this->idtext),
'get_texts_with_aides' => true,
'dbg' => array('liste_aides', 'Liste des aides du texte')
));
}
}
// date de creation
$this->abstract_date = $infos['abstractDate'];
if (isset($this->abstract_date) && $this->abstract_date != '0000-00-00' && $this->abstract_date != null) {
$infos['abstract_date'] = $this->getFormeDate($this->abstract_date, $GLOBALS['format_date'][$GLOBALS['lng']]);
$infos['abstract_date_us'] = $this->abstract_date;
}
if ($infos['statut']) {
$infos['statut'] = $this->statut = $infos['statut'];
// incomplet ?
if ($infos['statut'] == 1) {
$infos['validation_encours'] = true;
}
if ($infos['statut'] == 0) {
$infos['incomplet'] = true;
}
if ($infos['statut'] > 1) {
$infos['valide'] = true;
}
}
// utilisateur
if (isset($this->idextranetuser)) {
$infos['idextranetuser'] = $this->idextranetuser;
}
// récupèrer l'illustration
if (!empty($params_data['get_illustration'])) {
if (!empty($params_data['get_illustration']['format'])) {
$illustrations = $conn->getRepository(Contents::class)->getIllustrations($infos['idtext'], 'texts', 'class_couv', $params_data['get_illustration']['format']);
} else {
$illustrations = $conn->getRepository(Contents::class)->getIllustrations($infos['idtext'], 'texts', 'class_couv');
}
if (!empty($illustrations)) {
// illustrations
$infos['illustrations'] = $illustrations['illustrations'];
// vignettes
if (!empty($illustrations['vignette_object'])) {
$infos['vignette_object'] = $illustrations['vignette_object'];
}
}
}
$this->loadResult($infos);
return $infos;
}
// }}}
// {{{ getInfosObject()
/** Alias de getInfosText
*
* @access public
* @param int $idobject identifiant
* @return array
* @see getInfosText()
*/
public function getInfosObject($idobject = null)
{
return $this->getInfosText($idobject);
}
// }}}
// {{{ getTranslateTitle()
/** Recherche des titre traduit
*
* chercher le titre traduit du texte dans une langue donnée
*
* @access public
* @param int $idtext Identifiant du texte
* @param string $lng Identifiant de la langue
* @param bool $all afficher toutes les infos
*/
public function getTranslateTitle($idtext = null, $lng = null, $all = null)
{
try {
//requête qui va chercher le titre du texte dans une langue donnée
$sql = 'SELECT t.idtext, t.title, t.date, t.country, p.firstname, p.lastname
FROM texts t, text_traduction tt, text_translator ttr, persons p
WHERE t.idtext=tt.idtexttraduction
AND t.idtext=ttr.idtext
AND ttr.idperson=p.idperson
AND t.language=\'' . $this->escape($lng) . '\' AND tt.idtext=' . ((int)$idtext) . ' AND t.publish=1';
$res = $this->query($sql);
if ($res->numRows() > 0) {
while ($row = $res->fetchRow()) {
if ($all == null) { // je veux tous le renseignements
$result['idtext'] = $row['idtext'];
$result['title'] = $row['title'];
$result['date'] = $row['date'];
$result['lastname'] = $row['lastname'];
$result['firstname'] = $row['firstname'];
$result['country'] = $row['country'];
} else { // je prend juste le titre traduit
$result = $row['title'];
}
}
return $result;
} else { // aucune traduction pour ce texte
if ($all == null) {
return [];
} else {
return null;
}
}
} catch (\Throwable $e) {
return null;
}
}
// }}}
// {{{ getPersons()
/** Personnes associées à un texte
*
* Liste et les personnes associèes à un texte.
* On peux effectuer un tri par type (auteur, traducteur, éditeur...)
*
* @access public
* @param int $idtext identifiant du texte
* @param string $type type recherché (auteur, traducteur...)
* @param string $type_contact non implémenté
* @return array
*/
public function getPersons($idtext = null, $type = 'text_author')
{
if (empty($idtext) && isset($this->idtext)) $idtext = $this->idtext;
$infos_link = $this->getRelationsArray($type);
if (!empty($infos_link)) {
return $this->getLinkedObject($infos_link, $idtext, $infos_link['type'], 'texts');
}
}
/// }}}
// {{{ getAuthors()
/** Auteurs d'un texte
*
* Liste les auteurs d'un texte (ou du texte orginal d'une traduction)
*
* @access public
* @param int $idtext identifiant du texte
* @return array
*/
public function getAuthors($idtext = null, $type = null)
{
if (empty($idtext)) $idtext = $this->idtext;
if (!empty($this->type)) $type = $this->type;
// on recupere le type si besoin
// if (empty($this->type) && empty($type)) {
$queryBuilder = $this->createQueryBuilder('t');
$queryBuilder->select('t.type')
->andWhere('t.idtext = :idtext')
->setParameter('idtext', $idtext);
$query = $queryBuilder->getQuery();
$data = $query->getOneOrNullResult(Query::HYDRATE_ARRAY);
$type = $this->type = (int)$data['type'];
if (empty($this->idtext)) {
$this->idtext = (int)$idtext;
}
// }
// si traduction, on récup l'id du texte original pour avoir l'auteur
if ($type == 1) {
$originalText = $this->getOriginalsTexts($idtext, 'text_traduction', 'idtexttraduction');
$idtext = key($originalText);
}
return $this->getPersons($idtext, 'text_author');
}
// }}}
// {{{ getTranslators()
/** Traducteurs d'un texte
*
* Liste les traducteurs d'un texte
*
* @access public
* @param int $idtext identifiant du texte
* @return array
* @see getPersons()
*/
public function getTranslators($idtext = null)
{
if (empty($idtext)) $idtext = $this->idtext;
return $this->getPersons($idtext, 'text_translator');
}
// }}}
// {{{ getOriginalsTexts()
/** Sélection des textes originaux
*
* Textes originaux dont dépend une traduction ou une adaptation
*
* @access public
* @param string $idtextlie Identifiant de l'adaptation ou de la traduction
* @param string $table Nom de la table de liaison (text_traduction, text_adaptation...)
* @params string $cle Nom de la clé de liaison
* @return array
*/
public function getOriginalsTexts($idtextlie = null, $table = 'text_traduction', $cle = 'idtexttraduction', $params = array())
{
if (empty($idtextlie)) {
$idtextlie = $this->idtext;
}
$query = 'SELECT t.idtext, t.title, t.type, t.language, t.date, t.url_clean
FROM texts t, ' . $table . ' tt
WHERE t.idtext=tt.idtext
AND tt.' . $cle . '=' . $idtextlie . '
ORDER BY t.title';
$texts = $this->getEntityManager()->getConnection()->fetchAllAssociativeIndexed($query);
if (!empty($params['get_authors']) && !empty($texts)) {
foreach ($texts as $k => $v) {
$texts[$k]['allauthors'] = $this->getAuthors($k, $v['type']);
}
}
return $texts;
}
// }}}
// {{{ orderByDefaut()
/** Classement par défaut
*
* Défini le tri par défaut pour les requêtes de type SELECT
*
* @access public
* @return string
*/
public function orderByDefaut($order = null)
{
// tri par défaut
if (empty($order)) {
$order = 'texts.idtext';
}
return $order;
}
// }}}
// {{{ countSpectacles()
/** Compter le nombre de spectacle pour un texte et ses adaptations
*
*
* @access public
* @param int $idtext Identifiant du texte
* @return int
*/
public function countSpectacles($idtext = null, $publish = false, $params = array())
{
$idtext = (int)$idtext;
if ($idtext <= 0) return 0;
// On prépare les résultats pour la condition de la requête
$list_idtextadaptation = $this->queryCol('SELECT DISTINCT(ta.idtextadaptation) FROM text_adaptation ta WHERE ta.idtext=' . $idtext);
$list_idtext = $this->queryCol('SELECT t.idtext FROM texts t WHERE t.idtext=' . $idtext);
$resutat_function_textes = array_merge_recursive($list_idtext, $list_idtextadaptation);
$sql = 'SELECT COUNT(DISTINCT(s.idspectacle)) as total
FROM text_spectacle ts, spectacles s
WHERE ts.idspectacle=s.idspectacle';
// est-ce qu'on veux les publié ou pas ?
if ($publish != false) {
$sql .= ' AND s.publish=' . (int)$publish;
}
//compter aussi les adaptations
$sql .= ' AND (ts.idtext=' . $idtext . '
OR ts.idtext IN (
' . implode(',', $resutat_function_textes) . '
)';
//compter aussi les adaptations à l'étranger
if (array_key_exists('countforeignshow', $params)) {
$sql .= 'OR ts.idtext IN(
SELECT DISTINCT(t.idtext)
FROM
texts t,
text_traduction tt
WHERE
t.idtext = tt.idtexttraduction
AND tt.idtext = ' . $idtext . '
)';
}
$sql .= ')';
return $this->queryOne($sql);
}
// }}}
// {{{ countTranslations()
/** Compter le nombre de traductions pour un texte
*
* @access public
* @param int $idtext Identifiant du texte
* @return int
*/
public function countTranslations($idtext = null, $publish = false)
{
if (empty($idtext)) {
$sql = 'SELECT COUNT(DISTINCT(t.`idtext`)) as total
FROM texts t
WHERE t.`type`=1';
} else {
$sql = 'SELECT COUNT(DISTINCT(t.`idtext`)) as total
FROM text_traduction tt, texts t
WHERE tt.`idtexttraduction`=t.`idtext` AND tt.`idtext`=' . $idtext;
}
// est-ce qu'on veux les publié ou pas ?
if ($publish != false) {
$sql .= ' AND t.publish=' . $publish;
}
return $this->queryOne($sql);
}
// }}}
// {{{ getCountTranslations()
/** faut-il compter (dans des listes de resultats) ?
*
* @access public
* @param bool $count
* @return int
*/
public function getCountTranslations($count = true)
{
if ($count == true) {
$this->count_translations = true;
}
}
// }}}
// {{{ countLanguageTranslations()
/** Compter le nombre de langue de traduction pour un texte
*
* Défini le tri par défaut pour les requêtes de type SELECT
*
* @access public
* @param int $idtext Identifiant du texte
* @return int
*/
public function countLanguageTranslations($idtext = null)
{
$sql = 'SELECT COUNT(DISTINCT(t.language))
FROM texts t, text_traduction tt
WHERE tt.idtext=' . ((int)$idtext) . '
AND t.idtext=tt.idtexttraduction';
return $this->queryOne($sql);
}
// }}}
// {{{ getListLanguageTranslations()
/** Liste des langues d'un texte
*
* @access public
* @param int $idtext id du texte
* @return array
*/
public function getListLanguageTranslations($idtext)
{
//langue
$tr = $GLOBALS['tr'];
$sql = null;
// requete
$sql = 'SELECT DISTINCT(t.language),t.idtext
FROM texts t,text_traduction tt
WHERE tt.idtext=' . $idtext . '
AND t.idtext=tt.idtexttraduction GROUP BY t.language';
// execution de la requete
$this->query($sql);
while ($this->fetch()) {
$lg = $this->getLink('language', 'languages', 'id');
$lang[$this->idtext]['lang'] = $lg->$GLOBALS['lng'];
$lang[$this->idtext]['idtext'] = $this->idtext;
}
// retourner les enregistrements
return $lang;
}
// }}}
// {{{ getListSearch()
/** Liste des textes
*
* Pour les champs Ajax de relations et les recherches diverses
* permet de générer un tabelau associatif des titres des textes en
* fonction de critères de recherche alphabétique ou mots clès
*
* @access public
* @param string $lettres Pour la recherche alphabetique
* @param string $keywords Recherche par mots cles
* @return array
*/
public function getListSearch($lettre, $type = null, $keywords = null, $other, $type_object = null)
{
$queryBuilder = $this->createQueryBuilder('t');
$queryBuilder->select('partial t.{idtext,title,type,country,language}');
// uniquement les textes originaux
if ($type != 'text_spectacle' && $type != 'new_text' && $type != 'podcast_text' && $type != 'idobject' && $type_object != 'playlist') {
$queryBuilder->andWhere('t.type=0');
}
// selection par ordre alpha
if (!empty($lettre)) {
// $queryBuilder->andWhere('LOWER(LEFT(LTRIM(t.title),1))=\''.$this->escape($lettre).'\'');
$queryBuilder->andWhere('t.title LIKE \'' . $this->escape($lettre) . '%\'');
}
// recherche avec un mot cle
$list = $this->splitKeywords($keywords);
if ($list) {
if (!empty($list[$this->IDSTR])) {
// mots clés
foreach ($list[$this->IDSTR] as $s) {
$queryBuilder->andWhere('t.title LIKE \'%' . $s . '%\'');
}
}
if (!empty($list[$this->IDNUM])) {
// recherche par numéro d'id pour les mots clés numériques
$queryBuilder->orWhere('idtext IN (' . implode(',', $list[$this->IDNUM]) . ')');
}
}
// $this->orderBy('title');
$query = $queryBuilder->getQuery();
$texts = $query->getResult(Query::HYDRATE_ARRAY);
// $this->find();
$r = array();
foreach ($texts as $text) {
$this->loadResult($text);
// texte et auteur (ou collectif)
$r[$this->idtext] = $this->cutSentence($this->title, 45) . ' (' . $this->getOneAuthor() . ')';
// si c'est une traduction, ajouter le code langue
if ($this->type == 1) {
$r[$this->idtext] .= ' (' . $this->language . ')';
}
// si trouvé par id, on l'affiche en fin de titre
if (!empty($list[$this->IDNUM]) && in_array($this->idtext, $list[$this->IDNUM])) {
$r[$this->idtext] .= ' - n°' . $this->idtext;
}
}
$this->free();
return $r;
}
// }}}
// {{{ getOneAuthor()
/** Retourner sous forme de string le nom de l'auteur ou 'collectif'
*
* @param int $idtext Identifiant du texte
* @return string
*/
public function getOneAuthor($idtext = null)
{
$author = null;
if (empty($idtext)) {
$idtext = $this->idtext;
}
if ($authors = $this->getAuthors($idtext)) {
if (count($authors) > 1) {
$author = 'Collectif';
} else {
foreach ($authors as $key => $value) {
if (!empty($value['firstname'])) {
$author .= $value['firstname'] . ' ';
}
$author .= $value['lastname'];
}
}
}
return $author;
}
// }}}
// {{{ getObjectTitle()
/** Infos de l'item recherché
*
* Pour les champs Ajax de relations
*
* @access private
*/
public function getObjectTitle($idobject = null, $infos_object = array(), $params = array())
{
// si on n'a pas passé l'id a la méthode, on doit-être dans une boucle
if (!$idobject) {
$idobject = $this->idtext;
}
$fields = array('idtext', 'title', 'type', 'url_clean', 'valid');
// si on a les valeurs
if (!empty($infos_object)) {
foreach ($fields as $k => $v) {
if (array_key_exists($v, $infos_object)) {
$infos[$v] = $infos_object[$v];
}
}
} else { // si on n'a les valeurs dans une boucle
// si on n'a pas $this->title, c'est qu'il faut les infos
if (!isset($this->title)) {
$sql = 'SELECT ' . implode(',', $fields) . '
FROM ' . $this->__table . '
WHERE ' . $this->__idtable . '=' . ((int)$idobject);
$infos = $this->queryRow($sql);
if (empty($infos)) {
return false;
}
} else { // sinon, dans le tableau infos
foreach ($fields as $k => $v) {
if (isset($this->$v) && $this->$v != '') {
$infos[$v] = trim($this->$v);
}
}
}
}
// title
$title_view = $infos['title'];
// ajouter les metteurs en scène en chaine si demandé
if (!array_key_exists('noauthor', $params)) {
$infos_author = $this->getOneAuthor($infos['idtext']);
if (!empty($infos_author)) {
$title_view .= ' (' . $infos_author . ')';
$infos['title'] = $title_view;
}
}
// renvoyer un array plutôt que le titre (utile si on veux l'url)
if (array_key_exists('return_array', $params)) {
return $infos;
}
return $title_view;
}
// }}}
// {{{ getGenretextList()
/** Liste des genres de texte
*
* @access public
* @return array
*/
public function getGenretextList($plus = null, $visibility = null, $return_array = false)
{
$sql_genretext = 'SELECT idgenretext,genretext FROM genretexts ';
if (!empty($visibility)) {
$sql_genretext .= ' WHERE visibility IN (' . $this->arrayToIn($visibility) . ') ';
}
$sql_genretext .= ' ORDER BY ordergenre';
$genre_list = $this->getEntityManager()->getConnection()->fetchAllKeyValue($sql_genretext);
// objet de traduction
$tr = $GLOBALS['tr'];
if (!$return_array) {
foreach ($genre_list as $k => $v) {
$new_genre_list[$k] = $tr->trans($v . $plus);
}
} else {
foreach ($genre_list as $k => $v) {
$new_genre_list[$k]['name'] = $tr->trans($v . $plus);
$new_genre_list[$k]['code'] = str_replace('genre_', '', $v);
}
}
return $new_genre_list;
}
// }}}
// {{{ getTypeText()
/** Retrouver le type de texte
*
* @access public
* @param int idtype ID du type de texte
* @return string
*/
public function getTypeText($idtype)
{
if (empty($typetxt)) {
if ($idtype == 1) {
$typetxt = 'translate';
} else if ($idtype == 2) {
$typetxt = 'adaptation';
} else {
$typetxt = 'original';
}
}
return $typetxt;
}
// }}}
// {{{ getVignetteText()
/** Récupére la vignette d'un texte ou la cree si besoin
*
* @access public
* param int idtext identifiant du texte
* @return string
*/
public function getVignetteText($idtext = null, $format = array())
{
if (empty($idtext)) {
$idtext = $this->idtext;
}
// par default : image normal 100px x 100px qualite 75
if (!empty($format)) {
$set_format = $format;
} else {
$set_format = array('width' => $_ENV['VIGN_TEXT_WIDTH'], 'height' => $_ENV['VIGN_TEXT_HEIGHT'], 'direction' => 'thumb');
}
// generation par la classe Images
if (!isset($this->images)) {
$this->images = Images::getInstance($this->getEntityManager());
}
$this->images->setVignetteFormat($set_format);
return $this->images->getVignetteObject($idtext, 'texts', 'class_couv');
}
// }}}
// {{{ getInfosTextRow()
/** Retrouner un tableau standard dans les listes
*
*
* @param bool $allauthors afficher les auteurs
* @param bool $vignette trouver les vignettes
* @param bool $genre le genre
* @param bool $tabpublisher publisher sous forme de tableau
* @access public
* @return array
*/
public function getInfosTextRow($allauthors = true, $vignette = true, $genre = false, $tabpublisher = true, $params = array())
{
$month = array(
1 => 'Janvier',
2 => 'Février',
3 => 'Mars',
4 => 'Avril',
5 => 'Mai',
6 => 'Juin',
7 => 'Juillet',
8 => 'Août',
9 => 'Septembre',
10 => 'Octobre',
11 => 'Novembre',
12 => 'Decembre',
);
$txt = array();
$idtext = $this->idtext;
// id du texte, titre, url, auteur du texte
$txt['idtext'] = $idtext;
$txt['title'] = $this->title;
$txt['url_clean'] = $this->url_clean;
if (isset($this->date)) {
$txt['date'] = $this->date;
}
$txt['textorder'] = $this->textorder;
// date d'écriture
if (isset($this->datewrite)) {
$txt['datewrite'] = $this->datewrite;
}
// text fictif
if (isset($this->textfictif)) {
$txt['textfictif'] = $this->textfictif;
}
if (isset($this->isbn)) {
$txt['isbn'] = $this->isbn;
}
if (isset($this->ean)) {
$txt['ean'] = $this->ean;
}
if (isset($this->nbpages)) {
$txt['nbpages'] = $this->nbpages;
}
if (isset($this->publication_year)) {
$txt['publication_year'] = $this->publication_year;
$publication_month_caractere[] = $publication_date[] = $txt['publication_year'];
}
if (isset($this->publication_month)) {
if (strlen($this->publication_month) == 1) {
$txt['publication_month'] = '0' . $this->publication_month;
} else {
$txt['publication_month'] = $this->publication_month;
}
$publication_date[] = $txt['publication_month'];
$txt['publication_month_caractere'] = $month[$this->publication_month];
}
// les auteurs du texte
if ($allauthors) {
$txt['allauthors'] = $this->noPunct($this->getAuthors($idtext));
$this->collectif($txt['allauthors'], 0, 3);
}
// si traduction, aussi le traducteur
if (isset($this->type) && $this->type == 1) {
$txt['alltranslators'] = $this->noPunct($this->getTranslators($idtext));
}
// date de publication complète
if (!empty($publication_date)) {
$txt['publication_date'] = join('-', $publication_date);
}
// date d'ajout
if (isset($this->dateinsert)) {
$txt['dateinsert'] = $this->dateinsert;
$txt['dateinsert_lng'] = $this->getFormeDate($this->dateinsert, $GLOBALS['format_date'][$GLOBALS['lng']]);
$txt['dateinsert_hour_lng'] = $this->getFormeDate($this->dateinsert, 'H:i');
}
// l'editeur
if (isset($this->url_clean_publisher) && $this->url_clean_publisher != '') {
if (!empty($params['api'])) {
$txt['publisher'][$this->idcontact] = array(
'organisation' => $this->organisation,
'url_clean' => $this->url_clean_publisher,
);
} elseif ($tabpublisher) {
$txt['publisher']['organisation'] = $this->organisation;
$txt['publisher']['url_clean'] = $this->url_clean_publisher;
} else {
$txt['publisher'] = $this->organisation;
$txt['url_clean_publisher'] = $this->url_clean_publisher;
}
}
// vignette de base
if ($vignette) {
if (is_array($vignette)) {
$format = $vignette;
} else {
$format = array();
}
$txt['vignette'] = $this->getVignetteText($idtext, $format);
$format['blur'] = true;
$txt['vignette_flou'] = $this->getVignetteText($idtext, $format);
}
// pour une traduction, il faut aussi le texte orginal
if (isset($this->type) && $this->type == 1) {
$txt['original_texts'] = $this->getOriginalsTexts($idtext);
}
// genre de texte (theatre si pas précisé)
if ($genre) {
if (isset($this->idgenretext)) {
$txt['idgenretext'] = $this->idgenretext;
} else {
$txt['idgenretext'] = 1;
}
// traduction du genre de text
if (isset($this->genretext)) {
$txt['genretext'] = $GLOBALS['tr']->trans($this->genretext);
}
}
// si c'est une traduction, id du texte original
if (isset($this->idtextoriginal)) {
$txt['idtextoriginal'] = $this->idtextoriginal;
}
// langue
if (isset($this->language)) {
$txt['language'] = $this->getNameLanguage($this->language);
}
// pays
if (isset($this->country)) {
$txt['country'] = $this->getNameCountry($this->country);
}
// statut et validation
if (isset($this->valid)) {
$txt['valid'] = $this->valid;
}
if (isset($this->publish)) {
$txt['publish'] = $this->publish;
}
if (isset($this->statut)) {
$txt['statut'] = $this->statut;
}
if (!empty($params['stylemore'])) {
$txt['stylemore'] = $params['stylemore'];
} else {
$txt['stylemore'] = array('imagep' => 'width:85px;', 'desctxt' => 'width:170px;');
}
return $txt;
}
// }}}
// {{{ getRelationsArray()
/** Tableau des relations
*
* @access public
* @param string|int $type le type de champ
*/
public function getRelationsArray($type = null)
{
// tout ça est dans la table "contacts"
$types_idcontact = array(
'publisher',
'idcontact_publisher',
'idcontact_translation',
'idcontact_performing',
'source',
);
if (!empty($type) && in_array($type, $types_idcontact)) {
$precise_type = $type;
$type = 'idcontact';
} else {
$precise_type = null;
}
// author est avec la relation text_author
if (!empty($type) && $type == 'author') {
$type = 'text_author';
}
$array_types = array(
'text_trailer' => array(// documents multimedia associés
'type_join' => 'method',
'method' => 'getMultimediaList',
),
// contacts idcontact
'idcontact' => array(// contacts associés ?
'type_join' => 'simple',
'dest_table' => 'contacts',
'fields' => array('idcontact', 'organisation', 'lastname', 'firstname', 'type', 'url_clean', 'valid'),
'join_field_src' => $precise_type,
),
'text_classification' => array(// classifications associées
'field_input' => 'idclassification',
'type_join' => 'multiple',
'dest_table' => 'classifications',
'join_table' => 'text_classification',
'fields' => array('idclassification', 'classification', 'type'),
),
'text_translator' => array(// traducteurs
'type_join' => 'multiple',
'dest_table' => 'persons',
'join_field_src' => 'idtext',
'join_field_dest' => 'idperson',
'join_table' => 'text_translator',
'fields' => array('idperson', 'lastname', 'firstname', 'url_clean', 'valid'),
'sql_more' => ' ORDER BY j2.classement ASC',
),
'text_author' => array(// auteurs
'type_join' => 'multiple',
'dest_table' => 'persons',
'join_field_src' => 'idtext',
'join_field_dest' => 'idperson',
'join_table' => 'text_author',
'fields' => array('idperson', 'lastname', 'firstname', 'url_clean', 'valid'),
'sql_more' => ' ORDER BY j2.classement ASC',
),
'text_traduction' => array(// texts originaux liés à la traduction
'type_join' => 'multiple',
'dest_table' => 'texts',
'join_field_src' => 'idtexttraduction',
'join_field_dest' => 'idtext',
'join_table' => 'text_traduction',
'fields' => array('idtext', 'title', 'type', 'url_clean', 'valid'),
'title_params' => array('noauthor' => true), // sans l'auteur
),
'text_adaptation' => array(// text originaux liés à l'adaptation
'type_join' => 'multiple',
'dest_table' => 'texts',
'join_field_src' => 'idtextadaptation',
'join_field_dest' => 'idtext',
'join_table' => 'text_adaptation',
'fields' => array('idtext', 'title', 'type', 'url_clean', 'valid'),
'title_params' => array('noauthor' => true), // sans l'auteur
),
'text_person' => array(// persons liées à un texte
'type_join' => 'multiple',
'dest_table' => 'persons',
'join_table' => 'text_person',
'join_field_dest' => 'idperson',
'field_link' => 'idrole', //TODO
'fields' => array('idperson', 'lastname', 'firstname', 'url_clean', 'valid'),
),
'text_multimedia' => array(// classifications associées
'type_join' => 'multiple',
'dest_table' => 'multimedias',
'join_table' => 'object_multimedia',
'join_table_object' => 'texts',
//'join_table_constraint' => 'object_multimedia.object=\'texts\' AND object_multimedia.idobject=?',
'fields' => array('idmultimedia', 'sujet_titre', 'url_clean'),
),
// idextranetuser idtext
'idextranetuser' => array(// utilisateur associé
'type_join' => 'simple',
'dest_table' => 'extranetusers',
'join_field_src' => 'idextranetuser', // jointure
'fields' => array('idextranetuser', 'login', 'email'),
'description' => 'Utilisateur associé au texte',
'silent_delete_relation' => true,
),
);
if (!empty($array_types[$type])) {
$array_types[$type]['type'] = $type;
return $array_types[$type];
} else {
return $array_types;
}
}
// }}}
// {{{ getLinkedObject()
/** Particularité pour Texts
*
* @access public
* @see Theatre::getLinkedObject()
*/
public function getLinkedObject($infos_link, $idobject, $type, $src)
{
$itemslist = $this->getLinkedObjectTrait($infos_link, $idobject, $type, $src);
foreach ($itemslist as $k => $v) {
if (!empty($v['lastname']) && $v['lastname'] == 'Collectif') {
$itemslist[$k]['collectif'] = true;
}
}
return $itemslist;
}
// }}}
// {{{ collectif()
/** Modifie le tableau pour les collectifs
*
*
* @param array le tableau des auteurs (ou traducteurs)
* @param int $nb nombre d'auteurs ou de traducteurs
* @param int $type 0=auteurs 1=traducteurs
* @access protected
* @return array
*/
protected function collectif(&$arr, $type = 0, $nb_supp = 1)
{
static $types = array(
0 => 'auteurs',
1 => 'traducteurs'
);
$nb = count($arr);
if ($nb <= $nb_supp || !isset($types[$type])) return;
$arr = array(1 => array(
'lastname' => '(' . $nb . ' ' . $types[$type] . ')',
'firstname' => 'Collectif',
'collectif' => true)
);
}
// }}}
// {{{ countAssociateTexts()
/** Compter le nb de textes associés à un objet
*
*
* @param string $object Type d'objet
* @param int $idobject Identifiant
* @param int $idclassification Classification
* @access public
* @return array
*/
public function countAssociateTexts($object, $idobject, $idclassification)
{
$infos_link = $this->getRelationsArray('text_person');
if (!empty($infos_link)) {
return $this->getLinkedObject($infos_link, $idobject, $infos_link['type'], 'texts');
}
}
// }}}
// {{{ getSQLTexts()
/** Générer la requete standard pour un text
*
* $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(
* 'select_by_text_or_adaptation' => text et adaptation,
* '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 getSQLTexts($params = array(), $special = array(), $debug = false)
{
// tables et champs
$tables_list = array(
'texts' => array(
/* @TODO Suppression de 'date' ticket #171 est-ce que d'autres pages vont bug suite à ça ? */
'fields' => array('title', 'url_clean', 'publication_year', 'publication_month', 'isbn', 'textfictif', 'dateinsert', 'textorder', 'type', 'publish', 'statut', 'valid'),
),
'contacts' => array(
'fields' => array('idcontact', 'url_clean as url_clean_publisher', 'organisation'),
),
);
// 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) {
// si le champ contient ' as '
if (strpos($f, ' as ') !== false) {
$ff = explode(' as ', $f);
$select_fields_array[] = 'T' . $al . '.`' . $ff[0] . '` as `' . $ff[1] . '`';
} else {
$select_fields_array[] = 'T' . $al . '.`' . $f . '`';
}
}
$al++;
}
// select de base
$sql_select = 'SELECT DISTINCT(T1.`idtext`), ' . join(',', $select_fields_array) . ',
CONCAT(T1.`publication_year`, T1.`publication_month`) AS publication_date,
CAST(CONCAT(T1.`publication_year`, T1.`publication_month`) AS DATE) AS publication_date_full ';
// select en plus
if (array_key_exists('select', $params)) {
$sql_select .= ',' . $params['select'];
}
// compte seulement
if (array_key_exists('count_only', $special)) {
$sql_select = 'SELECT COUNT(DISTINCT(T1.`idtext`)) as total ';
}
// from avec jointure entre texts/contacts
if (array_key_exists('join', $special)) {
$sql_from = ' FROM texts T1
LEFT JOIN contacts T2 ON T2.`idcontact`=T1.`idcontact_publisher` ';
} else {
foreach ($tables_list as $k => $v) {
$sql_from_tables[] = $v['table_alias'];
}
$sql_from = ' FROM ' . join(',', $sql_from_tables);
}
// selectionde table en plus
if (array_key_exists('from', $params)) {
if (is_array($params['from'])) {
foreach ($params['from'] as $k => $v) {
$sql_from .= ',' . $v . ' T' . $al;
// join avec la table principale ?
if (!empty($k) && $k == 'join') {
$params['where'] = ' T1.idtext=T' . $al . '.idtext';
}
}
$al++;
} else {
$sql_from .= ',' . $params['from'];
}
}
// where standard
$sql_where = ' WHERE 1 ';
// avec couv uniquement
if (array_key_exists('avec_couverture', $special)) {
$sql_from .= ' ,object_file of, files f, file_classification fc ';
$sql_where .= ' AND of.idfile=f.idfile
AND of.idobject=T1.idtext
AND fc.idfile=f.idfile
AND fc.idclassification=20
AND of.object=\'texts\' ';
}
// avec un contenu associé en particulier
if (!empty($special['idclassification'])) {
$sql_from .= ' ,object_content oc2, contents c2, content_classification cc2 ';
$sql_where .= ' AND oc2.idcontent=c2.idcontent
AND cc2.idcontent=c2.idcontent
AND oc2.idobject=T1.idtext
AND cc2.idclassification IN (' . join(',', $special['idclassification']) . ')
AND oc2.object=\'texts\' ';
}
// par classification
if (array_key_exists('by_classification', $special)) {
if (!is_array($special['by_classification'])) {
$sql_from .= ' ,text_classification tcl,classifications cl2';
$sql_where .= ' AND tcl.idtext=s.idtext
AND tcl.idclassification=cl2.idclassification';
if ($this->my_is_int($special['by_classification'])) {
$sql_where .= ' AND cl2.idclassification=' . ((int)$special['by_classification']) . ' ';
} else {
$sql_where .= ' AND cl2.classification=\'' . $this->escape($special['by_classification']) . '\' ';
}
} else {
$sql_from .= ' ,text_classification tcl,classifications cl2';
$sql_where .= ' AND tcl.`idtext`=T1.`idtext`
AND tcl.`idclassification`=cl2.`idclassification`';
$sql_where .= ' AND cl2.`idclassification` IN (' . $this->arrayToIn($special['by_classification']) . ') ';
}
}
$having_more = '';
// pour les playlists
if (!empty($special['playlists'])) {
if (!empty($special['playlists']['text'])) {
$sql_from .= ' ,`playlists` ';
$sql_where .= ' AND `playlists`.`idtext`=T1.`idtext` ';
}
if (!empty($special['playlists']['idclassifications'])) {
$sql_from .= ' ,`playlist_classification` ';
$sql_where .= ' AND `playlist_classification`.`idplaylist`=`playlists`.`idplaylist` ';
$sql_where .= ' AND `playlist_classification`.idclassification IN (' . $this->arrayToIn($special['playlists']['idclassifications']) . ') ';
}
if (!isset($special['playlists']['publish'])) {
$sql_where .= ' AND `playlists`.`publish`=1 ';
}
}
// pour les podcasts
if (!empty($special['podcasts'])) {
$sql_from .= ' ,`podcasts`,`podcast_text` ';
$sql_select .= ' , podcasts.idpodcast ';
if (!empty($special['podcasts']['type_podcast'])) {
//franceculture
if ($special['podcasts']['type_podcast'] == 'franceculture') {
$sql_where .= ' AND `podcasts`.`code_franceinter` IS NOT NULL ';
} //culturebox
else {
$sql_where .= ' AND `podcasts`.`code_ft` IS NOT NULL ';
}
}
$sql_where .= ' AND `podcast_text`.`idtext`= T1.`idtext` ';
$sql_where .= ' AND `podcasts`.`idpodcast`=`podcast_text`.`idpodcast` ';
if (!isset($special['podcasts']['publish'])) {
$sql_where .= ' AND `podcasts`.`publish`=1 ';
}
}
// par aide => le type d'aide = idaide
if (array_key_exists('aides', $special)) {
// jionture avec text_aide et aides
$sql_from .= ' ,text_aide tai, aides ai, aidecontacts aic';
$sql_where .= ' AND tai.`idtext`=T1.`idtext`
AND tai.`idaide`=ai.`idaide`
AND ai.`idaidecontact`=aic.`idaidecontact` ';
// recherche par l'aide'
if (!empty($special['aides']['idaide'])) {
$sql_where .= ' AND tai.`idaide`=' . ((int)$special['aides']['idaide']) . ' ';
}
// recherche par la catégorie d'aide
if (!empty($special['aides']['idaidecontact_or_type_aide']) && !empty($special['aides']['idaidecontact']) && !empty($special['aides']['type_aide'])) {
$sql_where .= ' AND ( aic.`idaidecontact`=' . ((int)$special['aides']['idaidecontact']) . ' OR ';
if (is_array($special['aides']['type_aide'])) {
$sql_where .= ' ai.`type_aide`IN (' . implode(',', $special['aides']['type_aide']) . ' ))';
} else {
$sql_where .= ' ai.`type_aide`=' . ((int)$special['aides']['type_aide']) . ' )';
}
} else {
if (!empty($special['aides']['idaidecontact'])) {
$sql_where .= ' AND aic.`idaidecontact`=' . ((int)$special['aides']['idaidecontact']) . ' ';
}
// recherche par la catégorie d'aide
if (!empty($special['aides']['type_aide'])) {
if (is_array($special['aides']['type_aide'])) {
$sql_where .= ' AND ai.`type_aide`IN (' . implode(',', $special['aides']['type_aide']) . ' ) ';
} else {
$sql_where .= ' AND ai.`type_aide`=' . ((int)$special['aides']['type_aide']) . ' ';
}
}
}
// recherche par le contact
if (!empty($special['aides']['idcontact'])) {
$sql_where .= ' AND tai.`idcontact`=' . ((int)$special['aides']['idcontact']) . ' ';
}
// rechercher l'année de l'aide
if (!empty($special['aides']['year'])) {
$sql_where .= ' AND YEAR(tai.`date_start`)=\'' . ((int)$special['aides']['year']) . '\' ';
}
// par période d'aide
if (!empty($special['aides']['period'])) {
if (!empty($special['aides']['period']['start'])) {
$sql_where .= ' AND (tai.`date_start` BETWEEN \'' . $special['aides']['period']['start'] . '\' AND \'' . $special['aides']['period']['end'] . '\') ';
}
}
if (!empty($special['aides']['get_by_nombres_aides'])) {
if (!empty($special['aides']['get_by_nombres_aides_val'])) {
$having_more .= ' HAVING COUNT(DISTINCT tai.idaide) = ' . (int)$special['aides']['get_by_nombres_aides_val'] . '';
} else {
$having_more .= ' HAVING COUNT(DISTINCT tai.idaide) > 1';
}
}
}
// recherche par traducteur
if (array_key_exists('type', $special) && $special['type'] == 'translation') {
$sql_from .= ' text_translator tt, persons p';
$sql_where .= ' AND tt.idtext=t.idtext AND p.idperson=tt.idperson AND T1.type=1';
}
// recherche par auteur
if (array_key_exists('authors', $special)) {
$sql_from .= ' ,text_author ta, persons p';
$sql_where .= ' AND ta.`idtext`=T1.`idtext`
AND p.`idperson`=ta.`idperson` ';
if ((isset($special['authors'][0]) && isset($special['authors'][1]))
&& !is_array($special['authors'][0]) && is_array($special['authors'][1])) {
$sql_where .= ' AND ta.`idperson` ' . $special['authors'][0] . ' (' . join(',', $special['authors'][1]) . ') ';
} else {
if (!empty($special['authors']['letter'])) {
$sql_where .= ' AND LOWER(LEFT(LTRIM(p.`lastname`),1))=\'' . $this->escape($special['authors']['letter']) . '\' ';
} else {
$sql_where .= ' AND ta.`idperson` IN (' . join(',', $special['authors']) . ') ';
}
}
}
// uniquement si pas de jointure
if (!array_key_exists('join', $special)) {
$sql_where .= ' AND T2.idcontact=T1.idcontact_publisher';
}
// genre de texte
if (!empty($special['genretext'])) {
$sql_where .= ' AND T1.idgenretext IN (' . $this->arrayToIn($special['genretext']) . ') ';
}
// paramètres en plus
if (array_key_exists('where', $params)) {
$sql_where .= $params['where'];
}
// publie
/*if(!array_key_exists('publish', $params)) {
$sql_where .= ' AND publish=1';
}*/
// par utilisateur
if (!empty($special['idextranetuser'])) {
$sql_where .= ' AND T1.idextranetuser=' . (int)$special['idextranetuser'] . ' ';
}
// type de texte
// recherche alpha
if (array_key_exists('alpha', $special)) {
if (is_array($special['alpha'])) {
foreach ($special['alpha'] as $k => $v) {
$sql_where .= ' AND ' . $k . ' REGEXP \'^' . $v . '\' ';
}
} else {
$sql_where .= ' AND T1.lastname REGEXP \'^' . $special['alpha'] . '\' ';
}
}
// recherche des textes
if (!empty($special['idtext'])) {
if (is_array($special['idtext'])) {
if (isset($special['idtext'][0]) && isset($special['idtext'][1]) && (!is_array($special['idtext'][0]) && is_array($special['idtext'][1]))) {
$sql_where .= ' AND T1.`idtext` ' . $special['idtext'][0] . ' (' . join(',', $special['idtext'][1]) . ') ';
} else {
$sql_where .= ' AND T1.`idtext` IN (' . join(',', $special['idtext']) . ') ';
}
} else {
$sql_where .= ' AND T1.`idtext` IN (' . $special['idtext'] . ') ';
}
}
// par période de publication
if (!empty($special['periode'])) {
if (!empty($special['periode']['from'])) {
$now = new DateTime(date('Y-m-d'));
$now->modify($special['periode']['from']);
$sql_where .= ' AND CAST(CONCAT(T1.`publication_year`,\'-\',T1.`publication_month`,\'-00\') AS DATE) BETWEEN \'' . $now->format('Y-m') . '-00\' AND \'' . date('Y-m') . '-00\' ';
} elseif (is_array($special['periode'])) {
$sql_where .= ' AND CAST(CONCAT(T1.`publication_year`,\'-\',T1.`publication_month`,\'-00\') AS DATE) BETWEEN \'' . $special['periode']['datestart'] . '\' AND \'' . $special['periode']['dateend'] . '\' ';
}
}
if (!empty($special['deja_paru'])) {
$sql_where .= ' AND CAST(CONCAT(T1.`publication_year`,\'-\',T1.`publication_month`,\'-00\') AS DATE)<=\'' . date('Y-m') . '-00\' ';
}
// par année de publication
if (!empty($special['year'])) {
$sql_where .= ' AND T1.`publication_year`=' . (int)$special['year'] . ' ';
}
// groupement par défaut
if (!isset($special['no_group'])) {
if (!array_key_exists('groupby', $params)) {
$groupby = ' GROUP BY T1.idtext ';
} else {
$groupby = ' GROUP BY ' . $params['groupby'];
}
} else {
$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'];
}
//$order = ' ORDER BY T1.publication_year '.$classement;
$order = ' ORDER BY CAST(CONCAT(T1.`publication_year`,\'-\',T1.`publication_month`,\'-00\') AS DATE) ' . $classement;
} else {
$order = ' ORDER BY ' . $params['order'];
}
// classement aléatoire
if (array_key_exists('random', $special)) {
$order = ' ORDER BY RAND() ' . $special['random'];
}
if (array_key_exists('no_order', $special)) {
$order = ' ';
}
// 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 = ' ';
}
}
$sql_global = $sql_select . $sql_from . $sql_where . $groupby . $having_more . $order . $limit;
return $sql_global;
}
// }}}
// {{{ countListTexts()
/** Compter la liste des texts
*
* @access public
* @param array $params_sql paramètre pour la requete SQL
* @param bool $debug mode débugage
* @return int
*/
public function countListTexts($params_sql = null, $debug = false)
{
// si pas de tableau
if (!isset($params_sql['special'])) {
$params_sql['special'] = array();
}
if (!isset($params_sql['params'])) {
$params_sql['params'] = array();
}
// si pas de limite => tout
if (empty($params_sql['params']['limit'])) {
$params_sql['params']['limit'] = 'all';
}
$params_sql['special']['count_only'] = true;
$params_sql['special']['no_group'] = true;
// construction de la requête avec le passage de paramètres
return $this->queryOne($this->getSQLTexts($params_sql['params'], $params_sql['special'], $debug));
}
// }}}
// {{{ getListTexts()
/** Récupére la liste des texts
*
* Récupére les texts 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 getListTexts($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();
}
// construction de la requête avec le passage de paramètres
$sql = $this->getSQLTexts($params_sql['params'], $params_sql['special'], $debug);
$params_row = array();
// style more ?
if (!empty($params['stylemore'])) {
$params_row['stylemore'] = $params['stylemore'];
} else {
$params_row['stylemore'] = array('imagep' => 'width:80px;', 'desctxt' => 'width:200px;');
}
// format de la vignette
if (!empty($params['vignette_format'])) {
$vignette_format = $params['vignette_format'];
} else {
$vignette_format = array('height' => $_ENV['VIGN_TEXT_HEIGHT'], 'width' => $_ENV['VIGN_TEXT_WIDTH'], 'direction' => 'thumb');
}
// paramètre de debug
$dbg = (empty($params_sql['dbg'])) ? array() : $dbg = $params_sql['dbg'];
// executer la requete
$this->query($sql, $dbg);
$txt = array();
// debug
$start_boucle = microtime(true);
if (!isset($params_sql['api'])) {
$params_row['api'] = true;
}
// mettre en forme chaque reponse
while ($this->fetch()) {
$text = $this->getInfosTextRow($this->idtext, $vignette_format, false, true, $params_row);
$text['publisher_first'] = true;
if (!empty($params['publisher_first_inverse'])) {
$text['publisher_first_inverse'] = true;
}
$txt[$this->idtext] = $text;
if (!empty($txt['translators'])) {
;
exit;
}
}
// debug de la boucle
if ($this->isTraceMode('list_object')) {
$this->setTraceInfos(array(
'execution_time_boucle' => (microtime(true) - $start_boucle),
'dbg' => $dbg,
));
}
// libère
$this->free();
return $txt;
}
// }}}
// {{{ getTextsPersons()
/** Trouver tous les texts d'une ou plusieurs personnes
*
* @access public
* @param string $type_text = type de texte
* @return array
*/
public function getTextsPersons($idperson, $typetext = 'all', $publish = 'all', $join = false)
{
// publié ou pas ou tus
if ($this->my_is_int($publish)) {
$sql_publish = ' AND t.`publish`=1 AND t.`valid`=1 ';
} else {
$sql_publish = ' ';
}
if (is_array($idperson)) {
$idpersons = join(',', $idperson);
} else {
$idpersons = $idperson;
}
// trouver les textes orginaux de cette personne
if ($typetext == 'all' || $typetext == 'original') {
$sql_author = 'SELECT t.`idtext`
FROM text_author ta
JOIN texts t ON ta.`idtext`=t.`idtext`
WHERE ta.`idperson` IN (' . $idpersons . ')' . $sql_publish;
$author = $this->queryAll($sql_author);
}
// trouver les adaptations des textes de cette personne
if ($typetext == 'all' || $typetext == 'adaptation') {
$sql_adaptation = 'SELECT tad.`idtextadaptation`
FROM text_adaptation tad
JOIN texts t ON t.`idtext`=tad.`idtext`
JOIN text_author ta ON t.`idtext`=ta.`idtext`
WHERE ta.`idperson` IN (' . $idpersons . ')' . $sql_publish;
$adaptation = $this->queryAll($sql_adaptation);
}
// trouver les traductions par cette personne
if ($typetext == 'all' || $typetext == 'translator') {
$sql_translator = 'SELECT t.`idtext`
FROM text_translator tt
JOIN texts t ON tt.`idtext`=t.`idtext`
WHERE
tt.`idperson` IN (' . $idpersons . ')' . $sql_publish;
$translator = $this->queryAll($sql_translator);
}
// trouver les traductions des textes de cette personne
if ($typetext == 'all' || $typetext == 'translation') {
$sql_translation = 'SELECT tt.`idtexttraduction`
FROM text_traduction tt
JOIN text_author ta ON tt.`idtext`=ta.`idtext`
JOIN texts t ON tt.`idtext`=t.`idtext`
WHERE ta.`idperson` IN (' . $idpersons . ')' . $sql_publish;
$translation = $this->queryAll($sql_translation);
}
$idtexts = array();
if (!empty($author)) {
foreach ($author as $k => $v) {
$idtexts[] = $v['idtext'];
}
}
if (!empty($adaptation)) {
foreach ($adaptation as $k => $v) {
$idtexts[] = $v['idtextadaptation'];
}
}
if (!empty($translator)) {
foreach ($translator as $k => $v) {
$idtexts[] = $v['idtext'];
}
}
if (!empty($translation)) {
foreach ($translation as $k => $v) {
$idtexts[] = $v['idtexttraduction'];
}
}
if ($join) {
return join(',', $idtexts);
}
return $idtexts;
}
// }}}
// {{{ countTexts()
/** Compter le nombre total de textes
*
* @access public
* @params int $type 0 ou 1 original ou traduction
* @params int $idcontact_publisher Identifiant d'un éditeur
* @return int
*/
public function countTexts($type = 0, $idcontact_publisher = null, $language = null)
{
$sql = 'SELECT COUNT(DISTINCT(`idtext`))
FROM texts WHERE 1 ';
if ($type != 'all') {
$sql .= ' AND `type`=' . $type;
}
if (!empty($idcontact_publisher)) {
if ($idcontact_publisher == 'all') {
$sql .= ' AND `idcontact_publisher` IS NOT NULL ';
} else {
$sql .= ' AND `idcontact_publisher`=' . (int)$idcontact_publisher;
}
}
if (!empty($language)) {
$sql .= ' AND `language`=' . $this->quote($language);
}
return $this->queryOne($sql);
}
// }}}
// {{{ getApiFields()
/** champs à renvoyer par l'API
*
* @access public
* @param array tableau de données
*/
protected function getApiFields()
{
return array(
'object' => 'url_clean',
'title' => 'title',
'url_clean' => 'permanent_url#(.*)#' . $_ENV['URL_THNET'] . '/textes/${1}/', // url complète
'type' => 'type',
'isbn' => 'isbn',
'allauthors->authors' => array(
'lastname' => 'lastname',
'firstname' => 'firstname',
'url_clean' => 'permanent_url#(.*)#' . $_ENV['URL_THNET'] . '/biographies/${1}/',
),
'alltranslators->translators' => array(
'object' => 'url_clean',
'lastname' => 'lastname',
'firstname' => 'firstname',
'url_clean' => 'permanent_url#(.*)#' . $_ENV['URL_THNET'] . '/biographies/${1}/',
),
'original' => array(
'object' => 'url_clean',
'title' => 'title',
'url_clean' => 'permanent_url#(.*)#' . $_ENV['URL_THNET'] . '/spectacles/${1}/', // url complète
'allauthors->authors' => array(
'lastname' => 'lastname',
'firstname' => 'firstname',
'url_clean' => 'permanent_url#(.*)#' . $_ENV['URL_THNET'] . '/biographies/${1}/',
),
),
'publisher->publishers' => array(
'object' => 'url_clean',
'organisation' => 'name',
'url_clean' => 'permanent_url#(.*)#' . $_ENV['URL_THNET'] . '/contacts/${1}/',
),
'vignette' => 'cover',
'dateinsert' => 'insert_date',
);
}
// }}}
// {{{ getTextsFromSpectacles()
/** récupèrer les textes à partir d'une liste de spectacle
*
* @access public
* @param array $list_spectacles Liste des spectacles
*/
public function getTextsFromSpectacles($list_spectacles, $params_sql = array(), $params_display = array())
{
$conn = $this->getEntityManager();
// retrouver des textes
foreach ($list_spectacles as $k => $v) {
if (!empty($v['idtext'])) {
$idtexts[$v['idtext']] = $v['idtext'];
}
}
// rechercher les textes
if (!empty($idtexts)) {
if (empty($params_display)) {
$params_display = array(
'stylemore' => array('imagep' => 'width:75px;', 'desctxt' => 'width:190px;'),
'vignette_format' => array('width' => 90, 'height' => 65, 'direction' => 'thumb')
);
}
if (empty($params_sql['params'])) {
$params_sql['params'] = array(
'limit' => 'all',
'order' => ' FIELD(T1.idtext, ' . implode(',', $idtexts) . ')'
);
}
if (empty($params_sql['special'])) {
$params_sql['special'] = array(
'idtext' => array('IN', $idtexts),
'join' => true,
);
}
if (!empty($params_sql['limit'])) {
$params_sql['params']['limit'] = $params_sql['limit'];
unset($params_sql['limit']);
}
$params_sql['dbg'] = array('texts_affiche_' . uniqid(), 'Textes des spectacles à l\'affiche');
$list_texts = $this->getListTexts($params_sql, $params_display);
if (!empty($list_texts) && !empty($params_display['hide_publishing_date'])) {
foreach ($list_texts as $k => $v) {
$list_texts[$k]['publication_year'] = null;
}
}
// associer texts et spectacles
$i = 0;
foreach ($list_spectacles as $k => $v) {
if (empty($v['collage']) && !empty($list_texts[$v['idtext']])) {
if (empty($list_texts_listes[$v['idtext']])) {
$list_texts_listes[$v['idtext']] = $list_texts[$v['idtext']];
}
if (!empty($list_texts_listes[$v['idtext']]) && array_key_exists($v['idtext'], $idtexts)) {
// gros dirty hack pour un texte qui a plusieurs spectacles
if (!empty($list_texts_listes[$v['idtext']]['spectacle'][1])) {
$id = uniqid();
$list_texts_listes[$id] = $list_texts[$v['idtext']];
$list_texts_listes[$id]['spectacle'][1] = $v;
if (!empty($params_sql['get_aides'])) {
$params_sql['get_aides']['special']['idtexts'] = array($v['idtext']);
$params_sql['get_aides']['dbg'] = array('aide_text_' . $v['idtext'], 'Aide pour le texte ' . $v['idtext']);
$list_texts_listes[$id]['aides'] = $conn->getRepository(Aides::class)->getListAides($params_sql['get_aides']);
}
} else {
$list_texts_listes[$v['idtext']]['spectacle'][1] = $v; // limite 1 spectacle
// trouver les aides du texte et éventuellement pour le contact courant
if (!empty($params_sql['get_aides'])) {
$params_sql['get_aides']['special']['idtexts'] = array($v['idtext']);
$params_sql['get_aides']['dbg'] = array('aide_text_' . $v['idtext'], 'Aide pour le texte ' . $v['idtext']);
$list_texts_listes[$v['idtext']]['aides'] = $conn->getRepository(Aides::class)->getListAides($params_sql['get_aides']);
}
}
}
}
}
return $list_texts_listes;
}
}
// }}}
// {{{ makeJsonLD()
/** Génére le code en js+ld pour les moteurs de recherche
*
*
* @access public
* @return string
*/
public function makeJsonLD($infos)
{
$tableau = array(
"@type" => "Book",
'bookFormat' => 'Paperback',
'inLanguage' => $infos['language'],
'name' => $infos['title'],
// 'numberOfPages' => $infos['nbpages'],
'url' => $_ENV['URL_THNET'] . 'textes/' . $infos['url_clean'],
'workExample' => array(
"@type" => "Book",
// 'datePublished' => $infos['publication_year'].'-'.$infos['publication_month'],
// 'isbn' => $infos['isbn'],
)
);
//L'illustration du livre
if (!empty($infos['illustrations'])) {
$tableau['image'] = $infos['illustrations'][0]['url_file_path'];
} else if (!empty($infos['vignette_object'])) {
$tableau['image'] = $infos['vignette_object'];
}
//Ajout de l'éditeur
if (!empty($infos['publisher']['organisation'])) {
$tableau['workExample']['publisher'] = $infos['publisher']['organisation'];
}
foreach ($infos['authors'] as $idperson => $person) {
$tableau['author'][] = array(
"@type" => "Person",
"familyName" => $person['lastname'],
"givenName" => $person['firstname'],
"name" => $person['view_name']
);
}
$jsonld = '
<script type="application/ld+json">
{
"@context": "http://schema.org",
"@type": "WebPage",
"mainEntity": ' . json_encode($tableau) . '
}</script>';
return $jsonld;
}
// }}}
}