Notice.php 53.8 KB
Newer Older
1
<?php
2 3 4
/**
 * Copyright (c) 2012, Agence Française Informatique (AFI). All rights reserved.
 *
Laurent's avatar
Laurent committed
5
 * BOKEH is free software; you can redistribute it and/or modify
6 7 8 9 10 11
 * it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE as published by
 * the Free Software Foundation.
 *
 * There are special exceptions to the terms and conditions of the AGPL as it
 * is applied to this software (see README file).
 *
Laurent's avatar
Laurent committed
12
 * BOKEH is distributed in the hope that it will be useful,
13 14 15 16 17
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
 *
 * You should have received a copy of the GNU AFFERO GENERAL PUBLIC LICENSE
Laurent's avatar
Laurent committed
18
 * along with BOKEH; if not, write to the Free Software
19
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA
20 21
 */

22
class NoticeLoader extends Storm_Model_Loader {
23 24
  use Trait_MemoryCleaner;

Patrick Barroca's avatar
Patrick Barroca committed
25 26 27
  public function getNoticesFromPreferences($preferences) {
    $requetes = Class_Catalogue::getRequetes($preferences);
    $notices = $this->findAll($requetes["req_liste"]);
28

Patrick Barroca's avatar
Patrick Barroca committed
29 30 31 32 33
    // Tirage aleatoire
    if ($preferences["aleatoire"] == 1) {
      shuffle($notices);
      $notices = array_slice($notices, 0, $preferences["nb_notices"]);
    }
34

Patrick Barroca's avatar
Patrick Barroca committed
35 36
    return $notices;
  }
37

38

Patrick Barroca's avatar
Patrick Barroca committed
39
  public function findFirstNoticeForClefChapeau($clef) {
Patrick Barroca's avatar
Patrick Barroca committed
40 41 42 43
    $parts = explode('-', $clef);
    $params = ['clef_chapeau' => $parts[0]];
    if (isset($parts[1]))
      $params['type_doc'] = $parts[1];
44

45
    return $this->findFirstBy($params);
Patrick Barroca's avatar
Patrick Barroca committed
46
  }
47

48

Patrick Barroca's avatar
Patrick Barroca committed
49 50 51
  public function getNoticeIdsByRequeteRecherche($req) {
    if (!$req)
      return [];
52

Patrick Barroca's avatar
Patrick Barroca committed
53 54 55
    $closure = function() use ($req) {
      return Zend_Registry::get('sql')->fetchAllByColumn($req);
    };
56

Patrick Barroca's avatar
Patrick Barroca committed
57 58 59 60 61
    return (new Storm_Cache())
      ->useImplodeExplodeSerialization()
      ->memoize([$req, __CLASS__, __FUNCTION__],
                $closure);
  }
62 63


Patrick Barroca's avatar
Patrick Barroca committed
64
  public function findAllByRequeteRecherche($req, $nb_par_page, $page_no=1 ) {
Laurent's avatar
Laurent committed
65 66 67 68
    return $this->findAllByIds($this->getNoticeIdsByRequeteRecherche($req),
                               $nb_par_page,
                               $page_no);
  }
69

70

Laurent's avatar
Laurent committed
71
  public function findAllByIds($ids, $nb_par_page, $page_no) {
72 73 74 75
    if ($nb_par_page) {
      $offset = ($page_no ? $page_no - 1 : 0) * $nb_par_page;
      $ids = array_slice($ids, $offset, $nb_par_page);
    }
76

Patrick Barroca's avatar
Patrick Barroca committed
77 78
    if (empty($ids))
      return [];
79

Patrick Barroca's avatar
Patrick Barroca committed
80
    return Class_Notice::getLoader()->findAllBy(['id_notice' => $ids,
81
                                                 'order' => 'FIELD(id_notice, '.implode(',', $ids).')']);
Patrick Barroca's avatar
Patrick Barroca committed
82
  }
83

84

Patrick Barroca's avatar
Patrick Barroca committed
85 86 87
  public function countBySQLSelect($req) {
    return fetchOne($req);
  }
88 89


Patrick Barroca's avatar
Patrick Barroca committed
90 91 92 93
  public function getNoticeByOAIIdentifier($identifier) {
    $parts = explode(':', $identifier);
    return Class_Notice::getLoader()->getNoticeByClefAlpha(end($parts));
  }
94 95


Patrick Barroca's avatar
Patrick Barroca committed
96 97 98
  public function getNoticeByClefAlpha($clef) {
    return Class_Notice::findFirstBy(['clef_alpha' => $clef]);
  }
99 100


Patrick Barroca's avatar
Patrick Barroca committed
101 102 103 104
  public function getAllNoticesByClefChapeau($clef) {
    return Class_Notice::findAllBy(['clef_chapeau' => $clef,
                                    'order' => 'tome_alpha desc']);
  }
105 106


Patrick Barroca's avatar
Patrick Barroca committed
107 108 109
  public function getAllNoticesByClefAlpha($clef) {
    return Class_Notice::findAllBy(['clef_alpha' => $clef]);
  }
110

111

Patrick Barroca's avatar
Patrick Barroca committed
112 113 114
  public function findAllByCatalogue($catalogue) {
    return Class_Catalogue::getLoader()->loadNoticesFor($catalogue);
  }
115

Patrick Barroca's avatar
Patrick Barroca committed
116 117 118 119
  public function findByUrl($url) {
    $frbr_link = new Class_FRBR_Link();
    if (!$clef_alpha = $frbr_link->extractKeyFromUrl($url))
      return;
120

Patrick Barroca's avatar
Patrick Barroca committed
121 122
    return Class_Notice::getNoticeByClefAlpha($clef_alpha);
  }
123

124

Patrick Barroca's avatar
Patrick Barroca committed
125
  public function getEarliestNotice() {
126 127 128
    $result = $this->findAllBy(['limit' => 1,
                                'created_at not' => null,
                                'order' => 'created_at asc']);
Patrick Barroca's avatar
Patrick Barroca committed
129 130
    if (0 == count($result))
      return null;
131

Patrick Barroca's avatar
Patrick Barroca committed
132 133
    return $result[0];
  }
134 135


Patrick Barroca's avatar
Patrick Barroca committed
136 137 138 139 140 141
  public function findAllAfter($record_id, $update_date) {
    $where = "id_notice > " . $record_id . " and date_maj >='" . $update_date . "'";
    return Class_Notice::findAllBy(['where' => $where,
                                    'order' => 'id_notice',
                                    'limit' => '100']);
  }
142 143 144 145


  public function indexNoveltyFacets() {
    $page = 1;
146
    while($records = Class_Notice::findAllBy(['where' => 'match(facettes) against("+(HNNNN* HNANA*)" in boolean mode)',
147 148 149 150 151 152 153 154
                                              'limitPage' => [$page, 100]])) {
      foreach($records as $record)
        $record->updateNoveltyFacets();

      $this->_cleanMemory();
      $page++;
    }
  }
155 156
}

157 158


159
class Class_Notice extends Storm_Model_Abstract {
Patrick Barroca's avatar
Patrick Barroca committed
160 161
  use Trait_TimeSource, Trait_Translator;

162 163 164 165
  const
    TYPE_BIBLIOGRAPHIC = 1,
    TYPE_AUTHORITY = 2;

Patrick Barroca's avatar
Patrick Barroca committed
166 167 168 169 170 171 172
  protected $_loader_class = 'NoticeLoader';
  protected $_table_name = 'notices';
  protected $_table_primary = 'id_notice';
  /** @var Class_NoticeUnimarc */
  protected $_notice_unimarc;
  protected $_has_many = ['exemplaires' => ['model' => 'Class_Exemplaire',
                                            'role' => 'notice',
173
                                            'dependents' => 'delete']];
Patrick Barroca's avatar
Patrick Barroca committed
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191

  protected
    $_titre_principal,
    $_auteur_principal,
    $_avis,
    $_moderated_avis,
    $_resume,
    $_matieres,
    $_editeur,
    $_langueCodes,
    $_first_exemplaire;

  protected $_default_attribute_values = ['type_doc' => 0,
                                          'annee' => null,
                                          'isbn' => null,
                                          'ean' => null,
                                          'titres' => '',
                                          'auteurs' => '',
192
                                          'other_terms' => '',
Patrick Barroca's avatar
Patrick Barroca committed
193 194 195 196 197 198 199 200 201 202 203 204 205
                                          'editeur' => '',
                                          'collection' => '',
                                          'date_maj' => '',
                                          'collection' => '',
                                          'matieres' => '',
                                          'dewey' => '',
                                          'tome_alpha' => '',
                                          'clef_alpha' => '',
                                          'clef_chapeau' => '',
                                          'clef_oeuvre' => '',
                                          'facettes' => '',
                                          'url_vignette' => '',
                                          'url_image' => '',
206
                                          'date_creation' => '',
207 208
                                          'created_at' => null,
                                          'type' => self::TYPE_BIBLIOGRAPHIC];
Patrick Barroca's avatar
Patrick Barroca committed
209 210 211


  public function __construct() {
212
    parent::__construct();
Patrick Barroca's avatar
Patrick Barroca committed
213 214 215 216 217 218 219 220 221 222 223 224 225
    $this->_notice_unimarc = new Class_NoticeUnimarc();
  }


  public function initializeAttributes($datas) {
    parent::initializeAttributes($datas);
    if (isset($datas['unimarc']))
      $this->_notice_unimarc->setNotice($datas['unimarc']);
    return $this;
  }


  public function getAvisByUser($user)  {
226 227
    return Class_AvisNotice::findAllBy(['clef_oeuvre' => $this->getClefOeuvre(),
                                        'id_user' => $user->getId()]);
Patrick Barroca's avatar
Patrick Barroca committed
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
  }


  public function getAvis() {
    if (!isset($this->_avis)) {
      $avis_loader = Class_AvisNotice::getLoader();
      $this->_avis = $avis_loader->findAllBy(['clef_oeuvre' => $this->getClefOeuvre()]);
    }

    return $this->_avis;
  }


  public function getAvisBibliothecaire() {
    return Class_AvisNotice::filterByBibliothecaire($this->getAvis());
  }


  public function getAvisAbonne() {
    return Class_AvisNotice::filterByAbonne($this->getAvis());
  }


  public function getExemplairesByIdSite($id_site) {
    $all_exemplaires = $this->getExemplaires();
    $exemplaire_on_site = array();
    foreach ($all_exemplaires as $exemplaire) {
      if ($id_site == $exemplaire->getIdBib())
        $exemplaire_on_site []= $exemplaire;
    }

    return $exemplaire_on_site;
  }

  public function isEpub() {
    if ($this->getAlbum()
        && $this->getAlbum()->isEpub())
      return true;
    return false;

  }


  public function isRessourceNumerique() {
    $type_doc = Class_TypeDoc::find($this->getTypeDoc());
273 274 275
    return $type_doc ?
      $type_doc->isRessourceNumerique()
      : false;
Patrick Barroca's avatar
Patrick Barroca committed
276 277 278 279 280 281 282 283 284
  }


  /**
   * @return Class_Album
   */
  public function getAlbum() {
    if (!$this->isRessourceNumerique())
      return null;
285 286 287 288 289 290 291

    if(!$first_exemplaire = $this->getFirstExemplaire())
      return null;

    return ($album = Class_Album::find($first_exemplaire->getIdOrigine()))
      ? $album
      : Class_Album::findFirstBy(['id_origine' => $first_exemplaire->getIdOrigine()]);
Patrick Barroca's avatar
Patrick Barroca committed
292 293
  }

294

Patrick Barroca's avatar
Patrick Barroca committed
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
  /**
   * @return string
   */
  public function getTypeDocLabel() {
    $type_doc = Class_TypeDoc::find($this->getTypeDoc());
    return $type_doc ? $type_doc->getLabel() : '';
  }


  /**
   * @return Class_Exemplaire
   */
  public function getFirstExemplaire() {
    return isset($this->_first_exemplaire)
      ? $this->_first_exemplaire
      : $this->_first_exemplaire = Class_Exemplaire::findFirstBy(['id_notice' => $this->getId()]);
  }
312 313


Patrick Barroca's avatar
Patrick Barroca committed
314 315 316 317 318 319
  /**
   * @return boolean
   */
  public function isLivreNumerique() {
    return ($this->getTypeDoc() == Class_TypeDoc::LIVRE_NUM);
  }
320 321


Patrick Barroca's avatar
Patrick Barroca committed
322 323 324 325 326 327
  /**
   * @return Class_Notice
   */
  public function beLivreNumerique() {
    return $this->setTypeDoc(Class_TypeDoc::LIVRE_NUM);
  }
328 329


Patrick Barroca's avatar
Patrick Barroca committed
330 331 332 333 334 335 336 337 338 339 340 341 342
  /**
   * @return Class_Notice
   */
  public function beEPUB() {
    return $this->setTypeDoc(Class_TypeDoc::EPUB);
  }

  /**
   * @return Class_Notice
   */
  public function beSite() {
    return $this->setTypeDoc(Class_TypeDoc::SITE);
  }
llaffont's avatar
llaffont committed
343

Patrick Barroca's avatar
Patrick Barroca committed
344 345 346 347 348 349
  /**
   * @return Class_Notice
   */
  public function beLivre() {
    return $this->setTypeDoc(Class_TypeDoc::LIVRE);
  }
350 351


Patrick Barroca's avatar
Patrick Barroca committed
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
  public function getAllAvisPerSource($page = null) {
    $all_avis = array('bib' => array('liste' => $avis_bib = $this->getAvisBibliothecaires(),
                                     'note' => $this->getNoteMoyenneAvisBibliothecaires(),
                                     'nombre' => count($avis_bib),
                                     'titre' => 'Bibliothécaires'),
                      'abonne' => array('liste' => $avis_abon = $this->getAvisAbonnes(),
                                        'note' => $this->getNoteMoyenneAvisAbonnes(),
                                        'nombre' => count($avis_abon),
                                        'titre' => 'Lecteurs du portail'));

    foreach (array('Class_WebService_Babelio', 'Class_WebService_Amazon') as $provider_class) {
      $provider = new $provider_class();
      $source = strtolower(array_last(explode('_', $provider_class)));
      if ($data = $provider->getAvis($this, $page)) $all_avis[$source] = $data;
    }

    return $all_avis;
  }

371

372
  public function getAvisBibliothecaires() {
Patrick Barroca's avatar
Patrick Barroca committed
373 374
    return Class_AvisNotice::filterByBibliothecaire($this->getAvis());
  }
375

376

Patrick Barroca's avatar
Patrick Barroca committed
377 378 379
  public function numberOfAvisBibliothecaire() {
    return Class_AvisNotice::countBy(['abon_ou_bib' => 1, 'clef_oeuvre' => $this->getClefOeuvre()]);
  }
380

381 382

  public function getAvisAbonnes() {
Patrick Barroca's avatar
Patrick Barroca committed
383 384
    return Class_AvisNotice::filterByAbonne($this->getAvis());
  }
385

386

Patrick Barroca's avatar
Patrick Barroca committed
387 388 389
  public function numberOfAvisAbonne() {
    return Class_AvisNotice::countBy(['abon_ou_bib' => 0, 'clef_oeuvre' => $this->getClefOeuvre()]);
  }
390

391 392

  public function getNoteMoyenneAvisBibliothecaires() {
Patrick Barroca's avatar
Patrick Barroca committed
393 394
    return Class_AvisNotice::getNoteAverage($this->getAvisBibliothecaires());
  }
395

396 397

  public function getNoteMoyenneAvisAbonnes() {
Patrick Barroca's avatar
Patrick Barroca committed
398 399
    return Class_AvisNotice::getNoteAverage($this->getAvisAbonnes());
  }
400

401 402

  public function setAvis($list_avis) {
Patrick Barroca's avatar
Patrick Barroca committed
403 404
    $this->_avis = $list_avis;
  }
405

406

Patrick Barroca's avatar
Patrick Barroca committed
407 408 409 410
  public function setUnimarc($unimarc) {
    $this->getNoticeUnimarc()->setNotice($unimarc);
    return parent::setUnimarc($unimarc);
  }
411

412

413
  public function fetchUrlVignette() {
414
    return (new Class_Notice_Thumbnail())->fetchUrlVignette($this);
Patrick Barroca's avatar
Patrick Barroca committed
415
  }
416

417

Patrick Barroca's avatar
Patrick Barroca committed
418
  public function fetchUrlLocalVignette() {
419
    return (new Class_Notice_Thumbnail())->fetchUrlLocalVignette($this);
Patrick Barroca's avatar
Patrick Barroca committed
420
  }
421

422

423 424 425 426
  public function getFetchUrlVignette() {
    return $this->fetchUrlVignette();
  }

427

Patrick Barroca's avatar
Patrick Barroca committed
428
  public function fetchUrlImage() {
429
    return (new Class_Notice_Thumbnail())->fetchUrlImage($this);
Patrick Barroca's avatar
Patrick Barroca committed
430
  }
431 432


Patrick Barroca's avatar
Patrick Barroca committed
433
  public function hasVignette() {
434
    return (new Class_Notice_Thumbnail())->hasVignette($this);
Patrick Barroca's avatar
Patrick Barroca committed
435
  }
436

437

Patrick Barroca's avatar
Patrick Barroca committed
438 439 440
  public function isLivre() {
    return $this->getTypeDoc() == Class_TypeDoc::LIVRE;
  }
441

442

Patrick Barroca's avatar
Patrick Barroca committed
443 444 445
  public function isPeriodique() {
    return $this->getTypeDoc() == Class_TypeDoc::PERIODIQUE;
  }
446 447


Patrick Barroca's avatar
Patrick Barroca committed
448 449 450
  public function isDVD() {
    return $this->getTypeDoc() == Class_TypeDoc::DVD;
  }
451

452

453 454 455 456 457
  public function isDisc() {
    return $this->getTypeDoc() == Class_TypeDoc::DISQUE;
  }


458 459 460 461 462
  public function isUnknown() {
    return $this->getTypeDoc() == Class_TypeDoc::UNKNOWN;
  }


Patrick Barroca's avatar
Patrick Barroca committed
463 464 465
  public function isArteVOD() {
    return ($this->getTypeDoc() == Class_TypeDoc::ARTEVOD);
  }
466

467

Patrick Barroca's avatar
Patrick Barroca committed
468 469 470
  public function isArticleCms() {
    return ($this->getTypeDoc() == Class_TypeDoc::ARTICLE);
  }
471

472

Patrick Barroca's avatar
Patrick Barroca committed
473 474 475
  public function isRSS() {
    return ($this->getTypeDoc() == Class_TypeDoc::RSS);
  }
476

477

Patrick Barroca's avatar
Patrick Barroca committed
478 479 480
  public function isAudioRecord() {
    return ($this->getTypeDoc() == Class_TypeDoc::AUDIO_RECORD);
  }
481

482

483 484 485 486 487
  public function isDilicom() {
    return $this->getTypeDoc() == Class_TypeDoc::DILICOM;
  }


Patrick Barroca's avatar
Patrick Barroca committed
488 489 490
  public function isSite() {
    return ($this->getTypeDoc() == Class_TypeDoc::SITE);
  }
491 492


493 494 495 496 497 498 499
  public function isSigb() {
    return ($type = Class_TypeDoc::find($this->getTypeDoc()))
      ? $type->isSigb()
      : false;
  }


Patrick Barroca's avatar
Patrick Barroca committed
500 501 502
  public function getSite() {
    if (!$this->isSite())
      return null;
503

Patrick Barroca's avatar
Patrick Barroca committed
504 505
    return Class_Sitotheque::findFirstBy(['id_notice' => $this->getId()]);
  }
506

507

Patrick Barroca's avatar
Patrick Barroca committed
508 509 510
  public function isVignetteUpdatableToCacheServer() {
    return ((int)$this->getFamilleId() !== 0) &&  ((int)$this->getFamilleId() <= 5);
  }
511

512

Patrick Barroca's avatar
Patrick Barroca committed
513 514 515 516 517 518 519 520 521
  // ----------------------------------------------------------------
  // délégation des appels notice unimarc (Class_Notice n'hérite plus NoticeUnimarc)
  // ----------------------------------------------------------------
  public function __call($method, $args) {
    if (method_exists($this->_notice_unimarc, $method)) {
      if (!$this->_notice_unimarc->hasNotice() && isset($this->_attributes['unimarc']))
        $this->_notice_unimarc->setNotice($this->_attributes['unimarc']);
      return call_user_func_array(array($this->_notice_unimarc, $method), $args);
    }
522

Patrick Barroca's avatar
Patrick Barroca committed
523 524
    return parent::__call($method, $args);
  }
525 526


Patrick Barroca's avatar
Patrick Barroca committed
527 528 529
  public function get_subfield() {
    return call_user_func_array([$this->_notice_unimarc, 'get_subfield'], func_get_args());
  }
530 531


532 533 534 535 536 537
  public function set_subfield($zone, $sous_zone, $valeur) {
    $this->_notice_unimarc->set_subfield($zone, $sous_zone, $valeur);
    return $this;
  }


Patrick Barroca's avatar
Patrick Barroca committed
538 539 540
  public function getIsbnOrEan() {
    return $this->hasIsbn() ? str_replace("-", "", $this->getIsbn()) :  $this->getEan();
  }
541 542


Patrick Barroca's avatar
Patrick Barroca committed
543 544 545
  public function getAlphaKey() {
    return $this->getClefAlpha();
  }
546

547

Patrick Barroca's avatar
Patrick Barroca committed
548 549 550 551
  public function updateFacette($facettes) {
    $this->setFacettes(Class_Notice_Facettes::mergeFacettes($this->getFacettes(), $facettes));
    return $this;
  }
552

553

Patrick Barroca's avatar
Patrick Barroca committed
554 555 556 557
  public function deleteFacettes($facettes) {
    $this->setFacettes(Class_Notice_Facettes::removeFacettes($this->getFacettes(), $facettes));
    return $this;
  }
558

559

Patrick Barroca's avatar
Patrick Barroca committed
560 561 562 563 564 565 566 567 568 569 570 571 572
  /**
   * Rend la structure notice pour affichage liste
   */
  public function getNotice($champs = '') {
    // Champs de base
    $notice["id_notice"] = $this->getId();
    $notice["facettes"] = $this->getFacettes();
    $notice["isbn"] = $this->getIsbn();
    $notice["ean"] =  $this->getEan();
    $notice["type_doc"] = $this->getTypeDoc();
    $notice["tome_alpha"] = $this->getTomeAlpha();
    $notice["N"] = $this->getAnnee();
    $notice["clef_alpha"] = $this->getClefAlpha();
573

Patrick Barroca's avatar
Patrick Barroca committed
574 575
    // Id service (isbn ou ean)
    $notice["id_service"] = ($notice["isbn"]) ? str_replace("-", "", $notice["isbn"]) : $notice["ean"];
576

Patrick Barroca's avatar
Patrick Barroca committed
577 578 579 580
    // Champs demandés
    if ($champs) {
      for ($i = 0; $i < strlen($champs); $i++) {
        switch ($champs[$i]) {
Laurent's avatar
Laurent committed
581
          case "J": $notice["J"] = $this->getTitrePrincipal(); break;
Patrick Barroca's avatar
Patrick Barroca committed
582 583 584 585 586 587 588 589 590 591 592 593 594
          case "A": $notice["A"] = $this->getAuteurPrincipal(); break;
          case "E": $notice["E"] = $this->getEditeur(); break;
          case "F": $notice["F"] = $this->getCentreInteret(); break;
          case "C": $notice["C"] = $this->getCollections(true); break;
          case "O": $notice["O"] = $this->getNotes(); break;
          case "R": $notice["R"] = $this->getResume(); break;
          case "U": $notice["U"] = $unimarc; break;
          case "G": $notice["G"] = $this->getChampNotice("G", $notice["facettes"]); break;
        }
      }
    }
    return $notice;
  }
595 596


jgaimard's avatar
jgaimard committed
597 598 599
// ----------------------------------------------------------------
// Champ 200$b
// ----------------------------------------------------------------
Patrick Barroca's avatar
Patrick Barroca committed
600 601 602 603 604
  public function get200b()
  {
    $data = $this->get_subfield("200", "b");
    return $this->filtreTitre($data[0]);
  }
605

606 607 608
// ----------------------------------------------------------------
// Renvoie la clef chapeau et le no de partie
// ----------------------------------------------------------------
Patrick Barroca's avatar
Patrick Barroca committed
609 610 611 612
  public function getDataSerie($id_notice)  {
    $data = fetchEnreg("select clef_chapeau,tome_alpha from notices where id_notice=$id_notice");
    return $data;
  }
613 614 615 616

// ----------------------------------------------------------------
// Renvoie les articles d'un périodique
// ----------------------------------------------------------------
Patrick Barroca's avatar
Patrick Barroca committed
617 618 619
  public function getArticlesPeriodique() {
    // lire dans la base
    $datas = Class_Notice_SerialArticles::findAllBy(['clef_chapeau' => $this->getClefChapeau(),
620 621
                                                     'clef_numero' => $this->getTomeAlpha(),
                                                     'order' => 'id_article asc']);
Laurent's avatar
Laurent committed
622

Patrick Barroca's avatar
Patrick Barroca committed
623
    $articles = [];
Laurent's avatar
Laurent committed
624

Patrick Barroca's avatar
Patrick Barroca committed
625 626
    foreach ($datas as $enreg) {
      if (!$enreg->getUnimarc()) continue;
Laurent's avatar
Laurent committed
627

628 629
      $serial_article = new Class_Notice;
      $serial_article->getNoticeUnimarc()->setNotice($enreg->getUnimarc(), 0);
Laurent's avatar
Laurent committed
630

631 632
      $article = ["titre" => $serial_article->getTitrePrincipal()];
      if ($complement = $serial_article->getComplementTitre())
Patrick Barroca's avatar
Patrick Barroca committed
633
        $article["titre"] .= " : " . $complement;
Laurent's avatar
Laurent committed
634

635
      $auteurs = $serial_article->getAuteursUnimarc(true);
Patrick Barroca's avatar
Patrick Barroca committed
636
      $article["auteur"] = isset($auteurs[0]) ? $auteurs[0] : '';
637 638
      $article["pagination"] = $serial_article->getCollation();
      $note = $data = $serial_article->get_subfield("300", "a");
Patrick Barroca's avatar
Patrick Barroca committed
639
      $article["note"] = isset($note[0]) ? trim($note[0]) : '';
640 641
      $article["resume"] = $serial_article->getResume();
      $article["matieres"] = $serial_article->getMatieres();
Patrick Barroca's avatar
Patrick Barroca committed
642 643
      $articles[] = $article;
    }
644

Patrick Barroca's avatar
Patrick Barroca committed
645 646
    return $articles;
  }
647

648

Patrick Barroca's avatar
Patrick Barroca committed
649 650 651 652 653 654 655
  public function getCodeFacette($champ) {
    foreach ($this->getFacetCodes() as $item) {
      if ($item[0] == $champ)
        return $item;
    }
    return '';
  }
656

Laurent's avatar
Laurent committed
657

Patrick Barroca's avatar
Patrick Barroca committed
658 659 660
  public function getFacetCodes() {
    return array_filter(explode(' ', trim($this->getFacettes())));
  }
Laurent's avatar
Laurent committed
661 662 663



Patrick Barroca's avatar
Patrick Barroca committed
664 665 666 667 668 669 670 671 672
  public function getGenres() {
    $facets = Class_Notice_Facette::parseFacettesFromNoticeField($this->getFacettes());
    $genres = [];
    foreach($facets as $facet) {
      if ($facet->getCodeRubrique() == Class_CodifGenre::CODE_FACETTE)
        $genres []= Class_CodifGenre::find($facet->getValue());
    }
    return array_filter($genres);
  }
Laurent's avatar
Laurent committed
673

674

Patrick Barroca's avatar
Patrick Barroca committed
675 676 677 678 679 680
  public function getChampNotice($champ, $facettes = '') {
    if (in_array($champ,
                 [Class_CodifTags::CODE_FACETTE,
                  Class_CodifDewey::CODE_FACETTE,
                  Class_CodifPcdm4::CODE_FACETTE,
                  Class_CodifMatiere::CODE_FACETTE,
Laurent's avatar
Laurent committed
681
                  Class_TypeDoc::CODE_FACETTE,
Patrick Barroca's avatar
Patrick Barroca committed
682 683 684 685 686 687
                  Class_CodifGenre::CODE_FACETTE,
                  Class_CodifCentreInteret::CODE_FACETTE])) {
      $ret = [];
      $codification = Class_Codification::getInstance();
      $items = array_filter(explode(' ', trim($facettes)));
      foreach ($items as $item) {
688
        if (($item[0] != $champ) || (!$label = $codification->getLibelleFacette($item)))
Patrick Barroca's avatar
Patrick Barroca committed
689 690
          continue;

Patrick Barroca's avatar
Patrick Barroca committed
691 692
        $ret[] = $this->getReboundFieldForFacet($item,
                                                $label,
693 694 695
                                                $this->_('Rechercher tous les documents ayant comme %s: %s',
                                                         $codification->getNomChamp($champ),
                                                         $label));
Patrick Barroca's avatar
Patrick Barroca committed
696 697 698 699 700 701 702
      }
      return $ret;
    }

    switch ($champ) {
      case Class_CodifAuteur::CODE_FACETTE: return  $this->getAuteursUnimarc(false, true);
      case Class_Codification::CODE_TITRE: return  $this->getZonesTitre();
703
      case Class_Codification::CODE_EDITEUR: return  $this->getEditeurs();
Patrick Barroca's avatar
Patrick Barroca committed
704 705 706 707 708 709 710
      case Class_Codification::CODE_COLLECTION: return  $this->getCollections(true);
      case Class_Codification::CODE_NOTES: return  $this->getNotes();
      case Class_Codification::CODE_COLLATION: return  $this->getCollation();
      case Class_Codification::CODE_RESUME: return  $this->getResume();
      case Class_Codification::CODE_URL: return  $this->getUrls();
      case Class_Codification::CODE_ANNEE: return  $this->getAnnee();
      case Class_Codification::CODE_PRIX: return  $this->getPrix();
711
      case Class_CodifLangue::CODE_FACETTE: return  $this->getLangues();
Patrick Barroca's avatar
Patrick Barroca committed
712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824
      case Class_Codification::CODE_IDENTIFIANT: return  (new Class_Isbn($this->getIsbnOrEan()))->getAll()['isbn10'];
      case Class_Codification::CODE_NOUVEAUTE: return $this->isNouveaute() ? $this->_('Oui'): $this->_('Non');
    }

    return [];
  }


  public function getUrls() {
    return (new Class_Notice_Urls($this))->asArray();
  }

  public function getPrix() {
    return $this->get_subfield("010", "d");
  }

  public function hasTome() {
    if ($data = $this->get_subfield("461", "t")
        && strlen($this->getClefChapeau())>1)
      return true;
    return false;
  }

  public function getNoticesMemeSeries() {
    if (!$this->hasTome())
      return [];

    return $this->getLoader()->getAllNoticesByClefChapeau($this->getClefChapeau());

  }


  public function getNoticesSimilaires()  {
    $mots = [];
    $champs = ['titres','auteurs','editeur','collection','matieres','dewey'];

    foreach ($champs as $champ)
      $mots = array_merge($mots, explode(' ', trim($this->_get($champ))));

    $ix = new Class_Indexation();
    $mots = array_filter(array_map([$ix, 'getExpressionRecherche'],
                                   $mots));

    return Class_Notice::getLoader()
      ->findAllBy(['where' => "MATCH(".implode(',', $champs).") AGAINST('".implode(' ', $mots)."') AND id_notice != ".$this->getId(),
                   'limit' => 10]);
  }


  public function getTags($id_notice = null)  {
    if (!$id_notice)
      $id_notice = $this->getId();

    if (!$id_notice)
      return [];

    $ix = new Class_Indexation();

    // Preferences
    $champs = "titres,auteurs,collection,matieres,dewey";
    $champs_tags = "DPMZ";
    $nb_max = 50;
    $limite_notices = 15;

    // Lire les champs les plus significatifs
    $notice = fetchEnreg("select " . $champs . " from notices where id_notice=$id_notice");
    if (!$notice) return false;

    // Decoupage des mots index
    $recherche = '';
    foreach ($notice as $champ) {
      $mots = explode(" ", trim($champ));
      foreach ($mots as $mot) {
        $mot = $ix->getExpressionRecherche($mot);
        if ($mot)
          $recherche .= ' ' . $mot;
      }
    }

    // Lancer la requete
    $req = "select facettes from notices where MATCH(titres,auteurs,editeur,collection,matieres,dewey) AGAINST('" . $recherche . "') and id_notice !=$id_notice Limit 0," . $limite_notices;
    $items = fetchAll($req);

    // Récup des tags uniques et comptage des occurences
    if (!count($items)) return array();
    $temp = [];
    foreach ($items as $item)
      {
        $facettes = explode(" ", $item["facettes"]);
        if (!count($facettes)) continue;
        foreach ($facettes as $facette)
          {
            if (!trim($facette)) continue;
            if (strPos($champs_tags, substr($facette, 0, 1)) === false) continue;
            $temp[$facette] = fetchOne("select count(*) from notices where MATCH(facettes) AGAINST(' +" . $facette . " 'IN BOOLEAN MODE)");
          }
      }

    // Trier,Limiter le nombre et completer les infos
    if (!$temp) return array();
    arsort($temp);
    $nb = 0;
    foreach ($temp as $facette => $nombre)
      {
        $nb++;
        if ($nb > $nb_max) break;
        $tag["id"] = $facette;
        $tag["libelle"] = Class_Codification::getInstance()->getLibelleFacette($facette);
        $tag["nombre"] = $nombre;
        $tags[] = $tag;
      }
    return $tags;
  }
825 826 827 828

// ----------------------------------------------------------------
// Champ 856$b (identifiants cms sito et rss)
// ----------------------------------------------------------------
Patrick Barroca's avatar
Patrick Barroca committed
829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849
  public function getChamp856b()
  {
    $data = $this->get_subfield(856, "b");
    return isset($data[0]) ? $data[0] : '';
  }


  public function getTitreChapeau() {
    $titre = '';
    if ($data = $this->get_subfield("461", "t")) {
      return $this->filtreTitre($data[0]);
    }

    if ($titres = $this->get_subfield('200', 'a'))
      $titre = trim($titres[0]);
    // On cherche le chapeau et le n°
    return $this->filtreTitre($titre);

  }


850 851 852 853 854 855
  public function getRecordTitle() {
    $titres = $this->get_subfield('200', 'a');
    return $titres ? trim($titres[0]) : '';
  }


Laurent's avatar
Laurent committed
856
  public function getTitrePrincipal($separator = BR) {
Patrick Barroca's avatar
Patrick Barroca committed
857
    // 200$a
858
    $titre = $this->getRecordTitle();
Patrick Barroca's avatar
Patrick Barroca committed
859 860 861 862 863 864 865 866 867 868

    // On cherche le chapeau et le n°
    if ($data = $this->get_subfield("461", "t")) {
      $chapeau = $this->filtreTitre($data[0]);
      if ($chapeau)
        {
          if ($titre == $chapeau) $titre = "";
          $data=$this->get_subfield('461','v');
          $tome = isset($data[0]) ? $data[0] : null;
          if ($tome) $chapeau .= " n° " . $tome;
Laurent's avatar
Laurent committed
869
          if ($titre) $titre = $chapeau . $separator . $titre;
Patrick Barroca's avatar
Patrick Barroca committed
870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886
          else $titre = $chapeau;
        }
    }
    return $this->filtreTitre($titre);
  }


  public function getVolume() {
    $data = $this->get_subfield('461','v');
    return isset($data[0]) ? $data[0] : null;
  }


  public function setTitrePrincipal($titre) {
    $this->_notice_unimarc->set_subfield('200', 'a', $titre);
    return $this;
  }
887

888

jgaimard's avatar
jgaimard committed
889 890 891
// ----------------------------------------------------------------
// Titre + sous-titre paramétré pour affichage des listes
// ----------------------------------------------------------------
Patrick Barroca's avatar
Patrick Barroca committed
892 893 894
  public function getTitreEtSousTitre()
  {
    unset ($this->_titre_principal);
895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910
    return $this->getTitrePrincipal() . $this->getSubtitle();
  }


  public function getSubtitle() {
    $zones = Class_Profil::getCurrentProfil()->getZonesTitre();
    if (!count($zones))
      return '';

    $subtitle = '';
    foreach($zones as $zone) {
      $data = $this->get_subfield(substr($zone,0,3), substr($zone,4,1));
      if (!count($data)) continue;
      $subtitle .= ' : '.$this->filtreTitre($data[0]);
    }
    return $subtitle;
Patrick Barroca's avatar
Patrick Barroca committed
911
  }
912

jgaimard's avatar
jgaimard committed
913 914 915
// ----------------------------------------------------------------
// Label docs sonores
// ----------------------------------------------------------------
Patrick Barroca's avatar
Patrick Barroca committed
916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951
  public function getLabelSonore()
  {
    $bloc=$this->get_subfield('071');
    if(!count($bloc)) return;
    $data=$this->decoupe_bloc_champ($bloc[0]);
    foreach($data as $champ)
      {
        if($champ['code']=='a') $num=$this->filtreTitre($champ['valeur']);
        if($champ['code']=='b') $label=$this->filtreTitre($champ['valeur']);
      }
    $ret=$label." ; ".$num;
    return $ret;
  }


  public function isGam() {
    $data = $this->get_subfield('801', 'b');
    foreach($data as $champ)
      if ('GAM' == strtoupper($champ))
        return true;
    return false;
  }


  public function isCvs() {
    $data = $this->get_subfield('801', 'b');
    foreach($data as $champ)
      if ('CVS' == strtoupper($champ))
        return true;
    return false;
  }


  public function getMorceaux() {
    return Class_Notice_TracksReader::getTracksOf($this);
  }
952

953

954 955 956
// ----------------------------------------------------------------
// Complément du titre (1er seulement)
// ----------------------------------------------------------------
Patrick Barroca's avatar
Patrick Barroca committed
957 958 959 960 961 962 963
  public function getComplementTitre()
  {
    if (!$titre = $this->get_subfield("200", "e"))
      return '';
    $titre = $this->filtreTitre($titre[0]);
    return trim($titre);
  }
964

jgaimard's avatar
jgaimard committed
965 966 967
// ----------------------------------------------------------------
// ISSN
// ----------------------------------------------------------------
Patrick Barroca's avatar
Patrick Barroca committed
968 969 970 971 972
  public function getIssn()
  {
    $issn = $this->get_subfield("011", "a");
    return trim($issn[0]);
  }
973

jgaimard's avatar
jgaimard committed
974 975 976
// ----------------------------------------------------------------
// Mention d'edition
// ----------------------------------------------------------------
Patrick Barroca's avatar
Patrick Barroca committed
977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074
  public function getMentionEdition()
  {
    $titre = $this->get_subfield("205", "a");
    $titre = $this->filtreTitre($titre[0]);
    return trim($titre);
  }


  /**
   * @return array
   */
  protected function getZonesTitre() {
    $zones = Class_CosmoVar::get('unimarc_zone_titre');
    $zones = array_filter(explode(';', trim($zones)));
    return $this->_getTitresDansZones($zones);
  }


  /**
   * @param $zones array of string ex:200$a
   * @return array
   */
  protected function _getTitresDansZones($zones) {
    if (!is_array($zones) || empty($zones))
      return [];

    $titres = [];
    foreach ($zones as $elem) {
      $zone = substr($elem,0,3);
      $champ = strRight($elem, 1);
      $data = $this->get_subfield($zone);
      foreach ($data as $items) {
        $sous_champs = $this->decoupe_bloc_champ($items);
        foreach ($sous_champs as $item) {
          if ($item['code'] == $champ) {
            $item = $this->filtreTitre($item['valeur']);
            if ($item) $titres[] = $item;
          }
        }
      }
    }
    return $titres;
  }


  private function filtreTitre($titre) {
    $titre = str_replace([BR, '[', ']', '<', '>', '  ', chr(136)],
                         ["#BR# ", ' ', '', ' ', ' ', ' '],
                         $titre);

    if (substr($titre, 0, 1) == '?') {
      $deb = substr($titre, 0, 6);
      $titre = str_replace('?', '', $deb) . substr($titre, 6);
    }

    // filtrage caractères terminaux
    $filtre = ["/", ";", ",", ":"];
    foreach($filtre as $car) {
      if (substr($titre,-1,1) == $car)
        $titre = substr($titre, 0, strlen($titre)-1);
    }

    $titre = str_replace("#BR#",BR, $titre);
    return trim($titre);
  }


  public function getAuteurPrincipal() {
    if (!isset($this->_auteur_principal)) {
      $this->_auteur_principal = '';
      if (!$this->_auteur_principal=$this->getFirstAuthor()){
        if ($data = $this->get_subfield("200", "f"))
          $this->_auteur_principal = $data[0];
      }
    }

    return $this->_auteur_principal;
  }

  public function getFirstAuthor() {
    if (!$auteurs = $this->getAuteursUnimarc(true))
      return '';
    return $auteurs[0];
  }

  public function setAuteurPrincipal($auteur) {
    $this->_auteur_principal = $auteur;
    return $this;
  }


  public function getUnimarcZone($zone) {
    return $this->get_subfield($zone);
  }


  public function getAuteursUnimarc($auteurPrincipal = false, $getFonction = false) {

1075
    $indexation = Class_Indexation::getInstance();
Patrick Barroca's avatar
Patrick Barroca committed
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
    $auteurs = [];
    $zones = ['700', '710', '720', '730', '701', '702', '711', '712', '721', '722'];

    foreach ($zones as $zone) {
      if ($auteurPrincipal
          && $auteur = $this->_getPremierAuteurDansZone($zone, $indexation))
        return [$auteur];

      $auteurs = array_merge($auteurs, $this->_getAuteursDansZone($zone, $indexation, $getFonction));
    }

    // Si fonctions on constitue une nouvelle matrice détaillée
    if ($getFonction and 0 < count($auteurs))
      return $this->_getAuteursAvecFonctions($auteurs);

    return $auteurs;
  }


  /**
   * @param $zone string
   * @param $indexation Class_Indexation
   * @return string
   */
  protected function _getPremierAuteurDansZone($zone, $indexation) {
    $data = $this->get_subfield($zone);
    foreach ($data as $items) {
      $auteur = $this->_getAuteurDansSousChamps($this->decoupe_bloc_champ($items));
      $libelle = $auteur->nom . '|' . $auteur->prenom;

      if ($this->_isAuteurDansZoneValide($libelle, $indexation)) {
        return trim($auteur->prenom . ' ' . $auteur->nom);
      }
    }
    return '';
  }


  /**
   * @param $zone string
   * @param $indexation Class_Indexation
   * @param $avec_fonction boolean
   * @return array
   */
  protected function _getAuteursDansZone($zone, $indexation, $avec_fonction = false) {
    $auteurs = [];
    $data = $this->get_subfield($zone);
    foreach ($data as $items) {
      $libelle = $this->_getAuteurDansZone($items, $avec_fonction);

      if ($this->_isAuteurDansZoneValide($libelle, $indexation)) {
        $auteurs[] = $libelle;
      }
    }

    return $auteurs;
  }



  protected function getNatureDocs() {
    return $this->get_subfield('200','b');

  }


  /**
   * @param $data array
   * @param $indexation Class_Indexation
   * @param $avec_fonction boolean
   * @return string
   */
  protected function _getAuteurDansZone($data, $avec_fonction = false) {
    $auteur = $this->_getAuteurDansSousChamps($this->decoupe_bloc_champ($data));
    $libelle = $auteur->nom . '|' . $auteur->prenom;
    if ($avec_fonction)
      $libelle .= '|' . $auteur->fonction . '|' . $auteur->fonction_pergame;

    return $libelle;
  }


  /**
   * @param $auteur string
   * @param $indexation Class_Indexation
   * @return boolean
   */
  protected function _isAuteurDansZoneValide($auteur, $indexation) {
    return (strlen($auteur) > 2 or $indexation->isMotInclu($auteur))
      and striPos($auteur, 'ANONYME') === false;
  }


  /**
   * @param $data array
   * @return stdClass
   */
  protected function _getAuteurDansSousChamps($data) {
    $auteur = new stdClass();
Laurent's avatar
Laurent committed
1175

1176 1177
    $fonction_pergame = $auteur->nom = $auteur->prenom = $auteur->fonction_pergame = '';
    $fonctions = $fonctions_nanook = [];
Laurent's avatar
Laurent committed
1178

Patrick Barroca's avatar
Patrick Barroca committed
1179
    foreach ($data as $item) {
Laurent's avatar
Laurent committed
1180 1181
      $valeur = trim($item['valeur']);

1182
      if ($item['code'] == 'a') {
Laurent's avatar
Laurent committed
1183
        $auteur->nom = $valeur;
1184 1185 1186
        continue;
      }
      if ($item['code'] == 'b') {
Laurent's avatar
Laurent committed
1187
        $auteur->prenom = $valeur;
1188 1189 1190 1191
        continue;
      }

      if ($item['code'] == '4') {
1192 1193 1194
        $fonctions []= (is_numeric($valeur) && ($codif_fonction = Class_CodifAuteurFonction::find($valeur)))
          ? $codif_fonction->getLibelle()
          : $valeur;
1195 1196 1197
        continue;
      }

1198 1199
      if  ($item['code'] == 'g' && !$fonction_pergame) {
        $fonction_pergame = $valeur;
1200 1201
        continue;
      }
1202

1203
      if ($item['code'] == '6') {
1204
        $fonctions_nanook []= $valeur;
1205
      }
Patrick Barroca's avatar
Patrick Barroca committed
1206
    }
1207 1208 1209 1210 1211 1212 1213

    $auteur_sep = ', ';
    $auteur->fonction = implode($auteur_sep, $fonctions);
    $auteur->fonction_pergame = $fonctions_nanook
      ? implode($auteur_sep, $fonctions_nanook)
      : $fonction_pergame;

Patrick Barroca's avatar
Patrick Barroca committed
1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225
    return $auteur;
  }


  /**
   * @param $auteur array
   * @return array
   */
  protected function _getAuteursAvecFonctions($auteurs) {
    if (!is_array($auteurs) || empty($auteurs))
      return [];

1226
    $ix = Class_Indexation::getInstance();
Patrick Barroca's avatar
Patrick Barroca committed
1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246
    $result = [];
    foreach ($auteurs as $auteur) {
      $avec_fonction = $this->_getAuteurAvecFonction($auteur, $ix);
      if (!empty($avec_fonction))
        $result[] = $avec_fonction;
    }

    return $result;
  }


  /**
   * @param $auteur string formatted
   * @see getAuteurs
   */
  protected function _getAuteurAvecFonction($auteur, $indexation) {
    $item = explode('|', $auteur);
    $nom = $item[0];
    $prenom = $item[1];
    $fonction_pergame = $item[3];
1247
    $fonction = $fonction_pergame ? $fonction_pergame : $item[2];
Patrick Barroca's avatar
Patrick Barroca committed
1248

Laurent's avatar
Laurent committed
1249
    if (!$codif_auteur = Class_CodifAuteur::findByLastNameFirstName($nom, $prenom))
Patrick Barroca's avatar
Patrick Barroca committed
1250 1251 1252
      return [];

    $label = trim($prenom . ' ' . $nom) . (($fonction) ? ' (' . $fonction . ')': '');
Laurent's avatar
Laurent committed
1253
    return (new Class_Notice_FieldAuthor($codif_auteur))->setLabel($label);
Patrick Barroca's avatar
Patrick Barroca committed
1254 1255 1256
  }


Patrick Barroca's avatar
Patrick Barroca committed
1257
  public function getReboundFieldForFacet($facet, $label, $title) {
1258
    return (new Class_Notice_Field())
Meusburger's avatar
Meusburger committed
1259
      ->setId(substr($facet, 1))
1260
      ->setLabel($label)
Patrick Barroca's avatar
Patrick Barroca committed
1261 1262
      ->setTitle($title)

1263
      ->setUrlParams(['controller' => 'recherche',
Patrick Barroca's avatar
Patrick Barroca committed
1264 1265 1266 1267 1268
                      'action' => 'simple',
                      'code_rebond' => $facet,
                      'facettes' => null,
                      'facette' => null,
                      'serie' => null,
1269
                      'page' => null]);
Patrick Barroca's avatar
Patrick Barroca committed
1270 1271 1272 1273 1274 1275
  }


  public function getEditeur() {
    if ($this->_editeur)
      return $this->_editeur;
1276 1277 1278 1279 1280 1281 1282 1283 1284 1285

    $editors = $this->getEditeurs();
    return trim(reset($editors));
  }


  public function getEditeurs() {
    return ($data = $this->get_subfield('210', 'c'))
      ? array_filter($data)
      : [];
Patrick Barroca's avatar
Patrick Barroca committed
1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321
  }


  public function getEditeurAvecVille() {
    $editeur = $this->getEditeur();
    if ($data = $this->get_subfield('210', 'a'))
      $editeur .= ' (' . $this->filtreTitre($data[0]) . ')';
    return $editeur;
  }


  /**
   * @category testing
   */
  public function setEditeur($editeur) {
    $this->_editeur = $editeur;
    return parent::_set('editeur', $editeur);
  }


  public function getCollections($principale=false) {
    if (!$data = $this->get_subfield(225, "a")) $data = $this->get_subfield(410, "t");
    if(!$data) $data = [];

    if ($principale == true) {
      return isset($data[0]) ? $data[0] : '';
    }

    return $data;
  }


  public function getMatieres() {
    if (isset($this->_matieres))
      return $this->_matieres;

Patrick Barroca's avatar
Patrick Barroca committed
1322
    $matiere = [];
Patrick Barroca's avatar
Patrick Barroca committed
1323 1324 1325

    // Recup des zones matières dans les variables
    $zones = Class_CosmoVar::get('unimarc_zone_matiere');
Patrick Barroca's avatar
Patrick Barroca committed
1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338
    $zones = explode(';', trim($zones));
    foreach ($zones as $elem) {
      $data = $this->get_subfield(strLeft($elem, 3));
      $champs = strMid($elem, 3, 10);
      foreach ($data as $items) {
        $sous_champs = $this->decoupe_bloc_champ($items);
        $mot = '';
        foreach ($sous_champs as $item) {
          if ($item['code'] &&
              strpos($champs, $item['code']) !== false) {
            if ($mot)
              $mot.= ' : ';
            $mot .= $item['valeur'];
Patrick Barroca's avatar
Patrick Barroca committed
1339
          }
Patrick Barroca's avatar
Patrick Barroca committed
1340 1341
        }
        $matiere[] = trim($mot);
Patrick Barroca's avatar
Patrick Barroca committed
1342
      }
Patrick Barroca's avatar
Patrick Barroca committed
1343 1344 1345
    }

    return $matiere;
Patrick Barroca's avatar
Patrick Barroca committed
1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356
  }


  /**
   * @category testing
   * @param $matieres Array
   */
  public function setMatieres($matieres) {
    $this->_matieres = $matieres;
    return parent::_set('matieres', $matieres);
  }
1357 1358


1359 1360 1361
// ----------------------------------------------------------------
// CENTRE D'INTERET PERGAME
// ----------------------------------------------------------------
Patrick Barroca's avatar
Patrick Barroca committed
1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374
  public function getCentreInteret() {
    $interet = array();
    $data = $this->get_subfield("932");
    foreach ($data as $items) {
      $sous_champs = $this->decoupe_bloc_champ($items);
      foreach ($sous_champs as $item) {
        if ($item["code"] == "a") {
          if (trim($item["valeur"])) $interet[] = $item["valeur"];
        }
      }
    }
    return $interet;
  }
1375 1376 1377 1378

// ----------------------------------------------------------------
// Langues
// ----------------------------------------------------------------
Patrick Barroca's avatar
Patrick Barroca committed
1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427
  public function getLangues()  {
    return implode(', ', $this->getLanguesList());
  }


  public function getLanguesList()  {
    $codes = $this->getLangueCodes();
    if (0 == count($codes))
      return array();

    $langues = array();
    foreach ($codes as $code) {
      if ($langue = Class_CodifLangue::getLoader()->find($code))
        $langues[] = ($langue->getLibelle()) ? $langue->getLibelle() : $code;
    }
    return $langues;
  }


  public function getLangueCodes() {
    if ($this->_langueCodes)
      return $this->_langueCodes;

    $langues = array();
    $data = $this->get_subfield(101);
    foreach ($data as $items) {
      $sous_champs = $this->decoupe_bloc_champ($items);
      foreach ($sous_champs as $item) {
        if ('a' != $item['code'])
          continue;
        $code = substr(strtolower($item['valeur']), 0, 3);
        if ('und' == $code)
          continue;
        if ('fra' == $code)
          $code = 'fre';
        $langues[] = $code;
      }
    }
    return $langues;
  }


  /**
   * @category testing
   */
  public function setLangueCodes($codes) {
    $this->_langueCodes = $codes;
    return $this;
  }
1428

1429 1430 1431
// ----------------------------------------------------------------
// Notes bibliographiques
// ----------------------------------------------------------------
Patrick Barroca's avatar
Patrick Barroca committed
1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508
  public function getNotes()
  {
    $zones = array('300a', '303a', '304a', '305a', '306a', '307a', '308a', '310a', '312a', '313a', '314a', '316a', '317a', '320a', '321a', '323a', '334abcd', '337a', '345a');
    $notes = array();

    foreach ($zones as $elem)
      {
        $data = $this->get_subfield(substr($elem, 0, 3));
        $champs = substr($elem, 3);
        foreach ($data as $items)
          {
            $sous_champs = $this->decoupe_bloc_champ($items);
            $mot = '';
            foreach ($sous_champs as $item)
              {
                if (strpos($champs, $item['code']) !== false)
                  {
                    if ($mot) $mot.=', ';
                    $mot.=$item['valeur'];
                  }
              }
            if ($mot)
              $notes[] = trim($mot);
          }
      }
    return($notes);
  }


  public function getCollation() {
    if (!isset($this->_collation))  {
      $collation = '';
      $data = $this->get_subfield('215');
      foreach ($data as $items) {
        $sous_champs = $this->decoupe_bloc_champ($items);
        foreach ($sous_champs as $item) {
          if(strpos('; '.$collation.' ;','; '. $item["valeur"].' ;')=== false)
            {
              if ($collation) $collation .= " ; ";
              $collation.=$item["valeur"];
            }
        }
      }
      $collation=str_replace("+ ;","+",$collation);
      $collation=str_replace("; ;",";",$collation);
      $collation=str_replace(": ;",":",$collation);
      $this->_collation = $collation;
    }
    return $this->_collation;
  }


  /**
   * @return array
   */
  public function getCollations() {
    $collations = [];
    $data = $this->get_subfield('215');
    foreach ($data as $items) {
      $sous_champs = $this->decoupe_bloc_champ($items);
      foreach ($sous_champs as $item) {
        $collations[] = $item['valeur'];
      }
    }

    return $collations;
  }


  public function getResume() {
    if (isset($this->_resume))
      return $this->_resume;

    if ($album = $this->getAlbum())
      return $album->getDescription();

    $data = $this->get_subfield('330', 'a');
1509

1510
    return $this->_resume = (($resume = $this->_getHtmlSummary($data)) ?
1511
                             $resume : $this->_getTextSummary($data));
Patrick Barroca's avatar
Patrick Barroca committed
1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556
  }


  protected function _getHtmlSummary($values) {
    return $this->_getSummaryWith(
                                  $values,
                                  function($value) {
                                    return $this->_containsTags($value);
                                  });
  }


  protected function _getTextSummary($values) {
    $summary = $this->_getSummaryWith(
                                      $values,
                                      function($value) {
                                        return !$this->_containsTags($value);
                                      });

    if ($summary && substr($summary, -1) != '.')
      $summary .= '.';
    return $summary;
  }


  protected function _getSummaryWith($values, $closure) {
    $summary = '';
    foreach($values as $value)
      if ($closure($value) && strlen($value) > strlen($summary))
        $summary = $value;
    return $summary;
  }


  protected function _containsTags($value) {
    return $value != (new Zend_Filter_StripTags())->filter($value);
  }


  public function setResume($resume) {
    $this->_resume = $resume;
    return $this;
  }


1557 1558 1559
  /**
   * @param $visitor Trait_NoticeVisitor
   */
Patrick Barroca's avatar
Patrick Barroca committed
1560 1561 1562 1563 1564
  public function acceptVisitor($visitor) {
    $indexation = new Class_Indexation();
    $visitor->visitClefAlpha($this->getClefAlpha());
    $visitor->visitSerialTitle($this->_getTitresDansZones(['461$t']));
    $visitor->visitTitres($this->_getTitresDansZones(['200$a', '200$e']));
1565 1566
    $visitor->visitAuteurs(array_merge($this->_getAuteursDansZone('700', $indexation),
                                       $this->_getAuteursDansZone('701', $indexation)));
Patrick Barroca's avatar
Patrick Barroca committed
1567
    $visitor->visitContributeurs($this->_getAuteursDansZone('702', $indexation));
1568

Patrick Barroca's avatar
Patrick Barroca committed
1569 1570
    foreach ($this->getMatieres() as $matiere)
      $visitor->visitMatiere($matiere);
1571

Patrick Barroca's avatar
Patrick Barroca committed
1572
    $visitor->visitFormats($this->getCollations());
1573
    $visitor->visitResume($this->getResume());
Patrick Barroca's avatar
Patrick Barroca committed
1574
    $visitor->visitDateMaj($this->getDateMaj());
1575
    $visitor->visitCreatedAt($this->getCreatedAt());
Patrick Barroca's avatar
Patrick Barroca committed
1576 1577 1578 1579 1580 1581
    $visitor->visitAnnee($this->getAnnee());
    $visitor->visitEditeur($this->getEditeurAvecVille());
    $visitor->visitLangues($this->getLangueCodes());
    $visitor->visitTypeDoc($this->getTypeDoc());
    $visitor->visitNatureDoc($this->getNatureDocs());
    if ($this->hasVignette()) {
1582
      $visitor->visitVignette(Class_Url::absolute($this->fetchUrlLocalVignette()));
1583
      $visitor->visitImage(Class_Url::absolute($this->fetchUrlImage()));
Patrick Barroca's avatar
Patrick Barroca committed
1584 1585 1586 1587 1588 1589
    }
    $visitor->visitIsbn($this->getIsbn());
    $visitor->visitEan($this->getEan());
    $visitor->visitAlbum($this->getAlbum());
    $visitor->visitSource(array_merge($this->get_subfield('801', 'b'),
                                      $this->get_subfield('852', 'k')));
Ghislain Loas's avatar
Ghislain Loas committed
1590 1591

    $visitor->visitPermalink($this->getAbsoluteUrl());
Patrick Barroca's avatar
Patrick Barroca committed
1592 1593 1594
    $visitor->visitVolume($this->getVolume());
    $visitor->visitCollections($this->getCollections());
    $visitor->visitGenres($this->getGenres());
1595
    $visitor->visitItems($this); // $this to prevent call on getExemplaires here and overload requests
1596

Patrick Barroca's avatar
Patrick Barroca committed
1597
    foreach(Class_FRBR_Link::findByAnyKey($this->getClefAlpha()) as $link)
1598 1599
      $visitor->visitFrbrLink($link);

Laurent's avatar
Laurent committed
1600
    return $visitor;
Patrick Barroca's avatar
Patrick Barroca committed
1601 1602 1603
  }


Ghislain Loas's avatar
Ghislain Loas committed
1604 1605 1606 1607
  public function getAbsoluteUrl() {
    $permalink = new Class_Notice_Permalink();
    return $permalink->absoluteFor($this, null, true);
  }
Patrick Barroca's avatar
Patrick Barroca committed
1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652


  public function findAllResumes() {
    $avis = [];
    if($resume = $this->getResume())
      $avis[] = ['source' => 'Bibliothèque',
                 'texte' => $resume];

    $providers = ['Class_WebService_Fnac',
                  'Class_WebService_Babelio',
                  'Class_WebService_Premiere'];

    foreach ($providers as $provider_class) {
      $provider = new $provider_class();
      $avis = array_merge($avis, $provider->getResumes($this));
    }

    return $avis;
  }


  public function getLinksAsSource() {
    return Class_FRBR_Link::getRecordLinksForSource($this->getClefAlpha());
  }


  public function getLinksAsTarget() {
    return Class_FRBR_Link::getRecordLinksForTarget($this->getClefAlpha());
  }


  /**
   * @param $noticeUnimarc Class_NoticeUnimarc
   * @category testing
   * @return Class_Notice
   */
  public function setNoticeUnimarc($noticeUnimarc) {
    $this->_notice_unimarc = $noticeUnimarc;
    return $this;
  }


  /**
   * @return Class_NoticeUnimarc
   */
1653
  public function getNoticeUnimarc() {
Patrick Barroca's avatar
Patrick Barroca committed
1654 1655
    return $this->_notice_unimarc;
  }
llaffont's avatar
llaffont committed
1656 1657 1658



Patrick Barroca's avatar
Patrick Barroca committed
1659 1660 1661 1662 1663
  /**
   * @return String
   */
  public function toTabbedList() {
    $sep=chr(9);
1664

Patrick Barroca's avatar
Patrick Barroca committed
1665 1666 1667 1668 1669 1670
    $enreg  = Class_Codification::getInstance()->getLibelleFacette("T".$this->getTypeDoc()).$sep;
    $enreg .= $this->getTitrePrincipal().$sep;
    $enreg .= $this->getAuteurPrincipal().$sep;
    $enreg .= $this->getEditeur().$sep;
    $enreg .= implode(',', $this->getCollections()).$sep;
    $enreg .= $this->getAnnee().chr(10);
llaffont's avatar
llaffont committed
1671

Patrick Barroca's avatar
Patrick Barroca committed
1672 1673
    return $enreg;
  }
1674

1675

Patrick Barroca's avatar
Patrick Barroca committed
1676 1677 1678 1679 1680 1681
  public function hasExemplaireDisponible() {
    foreach ($this->getExemplaires() as $exemplaire)
      if ($exemplaire->isDisponible())
        return true;
    return false;
  }
1682

1683 1684

  public function getAvailabilityFromFacet() {
1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708
    $existing = $this->getAvailableLibrariesFromFacet();
    return !empty($existing);
  }


  public function getAvailableLibrariesFromFacet() {
    $existing = array_filter(
                             Class_Notice_Facette::parseFacettesFromNoticeField($this->getFacettes()),
                             function($facet) {
                               return $facet->isAvailability();
                             });

    $values = array_unique(
                           array_filter(
                                        array_map(function($facet)
                                                  {
                                                    return $facet->getValue();
                                                  },
                                                  $existing)));

    if(!$values)
      return [];

    return Class_Bib::findAllBy(['id_site' => $values]);
1709 1710 1711
  }


Patrick Barroca's avatar
Patrick Barroca committed
1712 1713 1714 1715 1716
  public function hasExemplaireReservable() {
    foreach ($this->getExemplaires() as $exemplaire)
      if ($exemplaire->isReservable())
        return true;
    return false;
1717

Patrick Barroca's avatar
Patrick Barroca committed
1718
  }
1719

Patrick Barroca's avatar
Patrick Barroca committed
1720 1721 1722
  public function renderOn($canvas) {
    return $canvas->renderNotice($this);
  }
1723

Patrick Barroca's avatar
Patrick Barroca committed
1724

Patrick Barroca's avatar
Patrick Barroca committed
1725 1726 1727 1728 1729
  public function getFamilleId() {
    if ($type_doc = Class_TypeDoc::find($this->getTypeDoc()))
      return $type_doc->getFamilleId();
    return 0;
  }
1730

1731

Patrick Barroca's avatar
Patrick Barroca committed
1732 1733 1734 1735 1736 1737
  public function isBookFamily() {
    return ($type_doc = Class_TypeDoc::find($this->getTypeDoc())) ?
      $type_doc->isBook() : false;
  }


Patrick Barroca's avatar
Patrick Barroca committed
1738 1739 1740
  public function isNouveaute() {
    return date('Y-m-d', self::getTimeSource()->time()) <= substr($this->getDateCreation(), 0, 10);
  }
1741 1742


Patrick Barroca's avatar
Patrick Barroca committed
1743 1744 1745
  public function isInPanier() {
    if(!$user=Class_Users::getIdentity())
      return false;
1746

Patrick Barroca's avatar
Patrick Barroca committed
1747 1748
    return $user->isNoticeInMyPanier($this);
  }
1749

1750

Patrick Barroca's avatar
Patrick Barroca committed
1751 1752 1753
  public function getPaniers() {
    if(!$user=Class_Users::getIdentity())
      return [];
1754

Patrick Barroca's avatar
Patrick Barroca committed
1755 1756
    return $user->getPaniersWhereICanFound($this);
  }
1757 1758


Patrick Barroca's avatar
Patrick Barroca committed
1759 1760 1761 1762
  public function getPaniersLibelles() {
    $list_panier = $this->getPaniers();
    if(($nb_paniers = count($list_panier)) < 1)
      return '';
1763