Bib.php 28.7 KB
Newer Older
llaffont's avatar
llaffont committed
1 2 3 4
<?php
/**
 * 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
llaffont's avatar
llaffont committed
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,
llaffont's avatar
llaffont committed
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
Ghislain Loas's avatar
Ghislain Loas committed
19
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA
llaffont's avatar
llaffont committed
20 21
 */

Patrick Barroca's avatar
Patrick Barroca committed
22
require_once dirname(__FILE__)."/CompositeBuilder.php";
23 24 25


class BibCSite extends Zend_Db_Table_Abstract {
Patrick Barroca's avatar
Patrick Barroca committed
26
  protected $_name = 'bib_c_site';
llaffont's avatar
llaffont committed
27 28 29 30 31
}



class BibLoader extends Storm_Model_Loader {
32 33
  use Trait_Translator;

Patrick Barroca's avatar
Patrick Barroca committed
34 35 36
  protected $_portail;

  public function findAllWithPortail() {
37
    $all_bibs = Class_Bib::findAllBy(['order' => 'libelle']);
Patrick Barroca's avatar
Patrick Barroca committed
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
    array_unshift($all_bibs, $this->getPortail());
    return $all_bibs;
  }


  public function findAllByWithPortail($args) {
    $bibs = $this->findAllBy($args);
    array_unshift($bibs, $this->getPortail());
    return $bibs;
  }


  public function findAllByIdZone($id_zone = 0) {
    $id_zone = (int)$id_zone;
    if (!$id_zone)
      return Class_Bib::findAllBy(['order' => 'ville']);
    return Class_Bib::findAllBy(['id_zone' => $id_zone,
                                 'order' => 'ville']);
  }

efalcy's avatar
efalcy committed
58

Patrick Barroca's avatar
Patrick Barroca committed
59
  public function getUserFriendlyBibs() {
60
    $all_bibs = Class_Bib::getLoader()->findAllBy(['order' => 'libelle']);
Patrick Barroca's avatar
Patrick Barroca committed
61 62
    $bibs_as_array = [];
    foreach($all_bibs as $bib) {
lbrun's avatar
lbrun committed
63
      $bibs_as_array[$bib->getId()] = $bib->getLabel();
Patrick Barroca's avatar
Patrick Barroca committed
64 65 66 67 68 69 70
    }
    return $bibs_as_array;
  }


  public function getPortail() {
    if (!isset($this->_portail))
71
      $this->_portail = $this->newInstanceWithId(0)->setLibelle($this->_('Portail'));
Patrick Barroca's avatar
Patrick Barroca committed
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
    return $this->_portail;
  }


  public function getBibsWithMail() {
    $all_bibs = Class_Bib::findAll();
    $all_bibs = array_filter($all_bibs, function($bib) {return $bib->hasMail() ? $bib->getLibelle(): '';});
    $libelles = [];
    foreach($all_bibs as $bib) {
      $libelles[$bib->getId()] = $bib->getLibelle();
    }
    return $libelles;
  }


  public function areAllBibsSelected($ids) {
    if(!is_array($ids))
      $ids = explode(',',$ids);

Laurent's avatar
Laurent committed
91
    $all_bibs = Class_Bib::findAllBy(['visibilite' => Class_Bib::V_DATA]);
Patrick Barroca's avatar
Patrick Barroca committed
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
    $all_bibs_ids = [];
    foreach($all_bibs as $bib)
      $all_bibs_ids[] = $bib->getId();

    sort($ids);
    sort($all_bibs_ids);
    return $ids == $all_bibs_ids;
  }


  public function getSelectedZones($ids) {
    if(!is_array($ids))
      $ids = explode(',',$ids);

    $zones = Class_Zone::findAll();

    $bibs_by_zones = [];
    foreach($zones as $zone) {
      $bibs_by_zones[$zone->getId()] = Class_Bib::findAllBy(['id_zone' => $zone->getId(),
Laurent's avatar
Laurent committed
111
                                                             'visibilite' => Class_Bib::V_DATA]);
Patrick Barroca's avatar
Patrick Barroca committed
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
    }

    $selected_zones = [];
    $select_bibs_not_in_zone = [];
    foreach($bibs_by_zones as $id => $bibs) {
      if(!$ids || !$bibs)
        continue;

      $bibs_ids = [];

      foreach($bibs as $bib)
        $bibs_ids[] = $bib->getId();

      if(0 == count(array_diff($bibs_ids, $ids))) {
        $selected_zones[] = $id;
        $ids = array_diff($ids, $bibs_ids);
      }

    }
    return [$selected_zones, $ids];
  }
133 134


135
  public function findAllWithRedmine() {
136 137
    return array_filter(array_unique(array_merge(Class_Bib::findAllBy(['redmine_login not' => '',
                                                                       'redmine_password not' => '']),
138
                                                 Class_Bib::findAllBy(['redmine_api_key not' => '']))));
139
  }
Ghislain Loas's avatar
Ghislain Loas committed
140 141


142
  public function findAllLabels() {
Laurent's avatar
Laurent committed
143 144 145 146 147
    return static::byIdLabels(Class_Bib::findAll());
  }


  public function byIdLabels($librairies) {
148
    $labels = [];
149
    foreach ($librairies as $library)
150
      $labels[$library->getId()] = $library->getLibelle();
151

152
    return $labels;
Ghislain Loas's avatar
Ghislain Loas committed
153
  }
Ghislain Loas's avatar
Ghislain Loas committed
154 155 156 157 158 159 160 161 162 163 164 165 166


  public function findAllWithCoordinates() {
    return Class_Bib::filterByCoordinates(Class_Bib::findAll());
  }


  public function filterByCoordinates($libraries) {
    return (new Storm_Model_Collection($libraries))
      ->select('hasLatitude')
      ->select('hasLongitude')
      ->getArrayCopy();
  }
llaffont's avatar
llaffont committed
167 168 169 170 171
}



class Class_Bib extends Storm_Model_Abstract {
172 173 174 175 176
  use
    Trait_PermissionTargetable,
    Trait_CustomFields,
    Trait_Translator,
    Trait_StaticFileSystem,
177
    Trait_TimeSource;
178 179 180 181 182 183

  const
    V_INVISIBLE = 0,
    V_NODATA = 1,
    V_DATA = 2,
    UPLOAD_MAX_SIZE = 250,
184
    STATE_OPENED = 'opened',
185
    STATE_OPENED_NOW = 'opened_now',
186
    BASE_PATH     = 'photobib/',
187 188
    THUMB_PREFIX = 'thumb_',
    CODE_FACETTE = 'B';
189

Laurent's avatar
Laurent committed
190 191
  protected static $_default_image_factory;

192 193 194
  private
    $_dataBaseError = "Problème d'accès à la base de données",
    $statut_bib;
llaffont's avatar
llaffont committed
195

Laurent's avatar
Laurent committed
196 197
  protected
    $_loader_class = 'BibLoader',
198

Laurent's avatar
Laurent committed
199
    $_table_name = 'bib_c_site',
Patrick Barroca's avatar
Patrick Barroca committed
200

Laurent's avatar
Laurent committed
201
    $_table_primary = 'ID_SITE',
Patrick Barroca's avatar
Patrick Barroca committed
202

Laurent's avatar
Laurent committed
203 204 205
    $_has_many = ['profils' => ['model' => 'Class_Profil',
                                'role' => 'bib',
                                'dependents' => 'delete'],
206

Laurent's avatar
Laurent committed
207 208 209
                  'users' => ['model' => 'Class_Users',
                              'role' => 'bib',
                              'dependents' => 'delete'],
llaffont's avatar
llaffont committed
210

Laurent's avatar
Laurent committed
211 212 213 214 215
                  'article_categories' => ['model' => 'Class_ArticleCategorie',
                                           'role' => 'bib',
                                           'scope' => ['ID_CAT_MERE' => 0],
                                           'order' => 'libelle',
                                           'dependents' => 'delete'],
216

Laurent's avatar
Laurent committed
217
                  'articles' => ['through' => 'article_categories'],
218

llaffont's avatar
llaffont committed
219

Laurent's avatar
Laurent committed
220 221 222 223 224
                  'sitotheque_categories' => ['model' => 'Class_SitothequeCategorie',
                                              'role' => 'bib',
                                              'scope' => ['ID_CAT_MERE' => 0],
                                              'order' => 'libelle',
                                              'dependents' => 'delete'],
225

Laurent's avatar
Laurent committed
226
                  'sitotheques' => ['through' => 'sitotheque_categories'],
227

228

Laurent's avatar
Laurent committed
229 230 231 232 233
                  'rss_categories' => ['model' => 'Class_RssCategorie',
                                       'role' => 'bib',
                                       'scope' => ['ID_CAT_MERE' => 0],
                                       'order' => 'libelle',
                                       'dependents' => 'delete'],
234

Laurent's avatar
Laurent committed
235 236 237 238 239
                  'feeds' => ['through' => 'rss_categories'],


                  'ouvertures' => ['model' => 'Class_Ouverture',
                                   'role' => 'bib',
240 241
                                   'order' => [
                                               'jour',
242
                                               'validity_end desc',
243
                                               'validity_start desc',
Patrick Barroca's avatar
Patrick Barroca committed
244
                                               'jour_semaine',
245 246
                                               'debut_matin'
                                   ],
247

Laurent's avatar
Laurent committed
248 249
                                   'dependents' => 'delete'],

250 251 252 253 254 255 256 257 258
                  'ouvertures_multimedia' => ['model' => 'Class_Ouverture',
                                              'role' => 'bib',
                                              'scope' => ['multimedia' => 1],
                                              'order' => ['jour',
                                                          'validity_end desc',
                                                          'validity_start desc',
                                                          'jour_semaine',
                                                          'debut_matin']],

Laurent's avatar
Laurent committed
259 260 261
                  'exemplaires' => ['model' => 'Class_Exemplaire',
                                    'role' => 'bib',
                                    'dependents' => 'delete'],
262

Laurent's avatar
Laurent committed
263
                  'localisations' => ['model' => 'Class_Localisation',
Patrick Barroca's avatar
Patrick Barroca committed
264
                                      'role' => 'bib',
Laurent's avatar
Laurent committed
265
                                      'order' => 'libelle'],
266

Laurent's avatar
Laurent committed
267 268 269 270 271 272 273 274
                  'plans' => ['model' => 'Class_Plan',
                              'role' => 'bib',
                              'order' => 'libelle']],

    $_belongs_to = ['zone' => ['model' => 'Class_Zone',
                               'role' => 'bib',
                               'referenced_in' => 'id_zone'],

275 276 277 278
                    'link_to_profil' => ['model' => 'Class_Profil',
                                         'role' => 'bib',
                                         'referenced_in' => 'link_to_profil_id'],

279 280 281
                    'lieu' => ['model' => 'Class_Lieu',
                               'role' => 'bib',
                               'referenced_in' => 'id_lieu']],
Laurent's avatar
Laurent committed
282

283
    $_default_attribute_values = ['visibilite' => self::V_INVISIBLE,
Laurent's avatar
Laurent committed
284 285 286
                                  'libelle' => '',
                                  'id_zone' => 0,
                                  'ville' => '',
287
                                  'adresse' => '',
Laurent's avatar
Laurent committed
288
                                  'mail' => '',
Laurent's avatar
Laurent committed
289
                                  'fond' => '',
Laurent's avatar
Laurent committed
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
                                  'telephone' => '',
                                  'aff_zone' => '',
                                  'interdire_resa' => 0,
                                  'google_map' => '',
                                  'photo' => '',
                                  'redmine_login' => '',
                                  'redmine_password' => '',
                                  'redmine_api_key' => '',
                                  'cp' => '',
                                  'lien_carto' => '',
                                  'horaire' => '',
                                  'inscription' => '',
                                  'pret' => '',
                                  'annexe' => '',
                                  'procure' => '',
305
                                  'closed_on_holidays' => true,
306
                                  'id_lieu' => 0,
307
                                  'rewrite_url' => '',
308
                                  'link_to_profil_id' => 0,
efalcy's avatar
efalcy committed
309
                                  'gln' => ''],
Laurent's avatar
Laurent committed
310

311
    $_file_uploaded = false,
Laurent's avatar
Laurent committed
312
    $_uploadHandler;
313

Patrick Barroca's avatar
Patrick Barroca committed
314
  public function __construct() {
315
    parent::__construct();
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
    $this->statut_bib = [$this->_('Invisible'),
                         $this->_('N\'envoie pas de données'),
                         $this->_('Envoie des données')];
  }


  public function describeAssociationsOn($associations) {
		$associations
			->add(new Storm_Model_Association_HasOne('int_bib', ['model' => 'Class_IntBib',
                                                           'role' => 'bib',
                                                           'referenced_in' => 'id_site']));
	}


  public function numberOfIntMajAutos() {
    return ($int_bib = $this->getIntBib())
      ? $int_bib->numberOfIntMajAutos()
      : 0;
Patrick Barroca's avatar
Patrick Barroca committed
334
  }
llaffont's avatar
llaffont committed
335 336


Ghislain Loas's avatar
Ghislain Loas committed
337 338 339 340 341 342 343 344 345 346 347 348
  public function getLieu() {
    if ($lieu = parent::_get('lieu'))
      return $lieu;

    return Class_Lieu::getLoader()
      ->newInstance()
      ->setAdresse($this->getAdresse())
      ->setCodePostal($this->getCp())
      ->setVille($this->getVille());
  }


Patrick Barroca's avatar
Patrick Barroca committed
349 350 351
  public function isPortail() {
    return $this->getId() === 0;
  }
352 353


Patrick Barroca's avatar
Patrick Barroca committed
354 355 356
  public function getAffZoneAsArray() {
    if (!$aff_zone = ZendAfi_Filters_Serialize::unserialize($this->getAffZone()))
      $aff_zone = [];
357

358 359
    return array_merge(['profilID' => '0',
                        'libelle' => $this->getVille(),
Patrick Barroca's avatar
Patrick Barroca committed
360 361
                        'posX' => 0,
                        'posY' => 0,
362
                        'posPoint' => 'gauche'],
Patrick Barroca's avatar
Patrick Barroca committed
363 364
                       $aff_zone);
  }
llaffont's avatar
llaffont committed
365 366


Patrick Barroca's avatar
Patrick Barroca committed
367
  public function getUrl() {
368 369 370
    if ($this->hasRewriteUrl())
      return Class_Url::assemble(['module' => $this->getRewriteUrl()], null, true);

371 372 373 374 375
    $parts = ($profil = $this->_getProfilForUrl())
      ? $profil->getUrlParts()
      : ['controller' => 'bib',
         'action' => 'bibview',
         'id' => $this->getId()];
Patrick Barroca's avatar
Patrick Barroca committed
376

377 378
    return Class_Url::assemble($parts, null, true);
  }
Patrick Barroca's avatar
Patrick Barroca committed
379 380


381 382 383 384 385
  protected function _getProfilForUrl() {
    return $this->hasLinkToProfil()
      ? $this->getLinkToProfil()
      // used on obsolete zone / map configuration
      : Class_Profil::find($this->getAffZoneAsArray()["profilID"]);
Patrick Barroca's avatar
Patrick Barroca committed
386 387 388
  }


389 390 391 392 393
  public function isClosedOnHolidays() {
    return $this->getClosedOnHolidays() == true;
  }


Patrick Barroca's avatar
Patrick Barroca committed
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
  public function getPosX() {
    return $this->getAffZoneKey('posX');
  }


  public function getPosY() {
    return $this->getAffZoneKey('posY');
  }


  public function getPosPoint() {
    return $this->getAffZoneKey('posPoint');
  }


409 410 411 412 413
  public function getLibelleAff() {
    return $this->getAffZoneKey('libelle');
  }


Patrick Barroca's avatar
Patrick Barroca committed
414 415 416 417 418
  public function getProfilId() {
    return $this->getAffZoneKey('profilID');
  }


419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
  public function isSIGBSendData() {
    return $this->getVisibilite() == static::V_DATA;
  }


  /** @return Class_Bib */
  public function ensureIntBib() {
    if (!$int_bib = Class_IntBib::find($this->getId()))
      $int_bib = Class_IntBib::newInstance(['id_bib' => $this->getId()]);

    $int_bib->setNomCourt($this->getVille())->save();
    return $this;
  }


  public function deleteIntBibRelated() {
    $id_bib = $this->getId();
    if (0 < Class_Exemplaire::countBy(['id_bib' => $id_bib]))
      return $this;

    Class_IntBib::deleteBy(['id_bib' => $id_bib]);
    Class_NoticeSuccincte::deleteBy(['id_bib' => $id_bib]);
    return $this;
  }


Patrick Barroca's avatar
Patrick Barroca committed
445 446 447 448 449 450 451 452 453 454 455 456 457 458
  public function getAffZoneKey($key) {
    if (!$aff_zone = ZendAfi_Filters_Serialize::unserialize($this->getAffZone()))
      return 0;

    if(!isset($aff_zone[$key]))
      return 0;

    return $aff_zone[$key];
  }


  public function getBibsBySite($id_site=0) {
    $where = '';
    if($id_site!=0)
459
      $where=" Where ID_SITE=" . (int)$id_site;
Patrick Barroca's avatar
Patrick Barroca committed
460 461 462 463 464 465 466 467 468 469 470 471 472 473

    $bibs=fetchAll("select * from bib_c_site".$where." order by LIBELLE");
    if ($bibs==false) $bibs = array();
    return $bibs;
  }


  // ----------------------------------------------------------------
  // Return un select avec la liste des bibs groupées par zone
  // ----------------------------------------------------------------
  public function getComboBib($id_bib=0,$id_zone=0,$all=true, $tag_name="bib") {
    $selectAll = '';
    if (!$id_bib) $selectAll = 'selected="selected"';
    $html[]='<select name="'.$tag_name.'" id="'.$tag_name.'" style="width:100%">';
474
    if($all) $html[]='<option value="0" '.$selectAll.'>** '.$this->_('Toutes').' **</option>';
efalcy's avatar
efalcy committed
475 476

    $zone_array = Class_Zone::getZones($id_zone);
Patrick Barroca's avatar
Patrick Barroca committed
477 478
    foreach ($zone_array as $zone)
      {
efalcy's avatar
efalcy committed
479
        $html[]='<optgroup label="'.$zone->getLibelle().'" style="font-style:normal;color:#FF6600">';
efalcy's avatar
efalcy committed
480
        $bib_array = $zone->getBibs();
Patrick Barroca's avatar
Patrick Barroca committed
481 482 483 484
        // les bibs
        if(!$bib_array) continue;
        foreach ($bib_array as $bib)
          {
efalcy's avatar
efalcy committed
485 486
            if ($id_bib == $bib->getIdSite()) $selected='selected="selected"'; else $selected='';
            $html[]='<option style="color:#575757" value="'.$bib->getIdSite().'" '.$selected.'>'.$bib->getLibelle().'</option>';
Patrick Barroca's avatar
Patrick Barroca committed
487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509
          }
        $html[]='</optgroup>';
      }
    $html[]='</select>';
    return implode('',$html);
  }



  public function getBibById($id_bib)
  {
    try
      {
        $BibCSite = new BibCSite();
        $where = $BibCSite->getAdapter()->quoteInto('ID_SITE=?', $id_bib);
        return $fetch = $BibCSite->fetchRow($where);
      }catch (Exception $e)
        {
          logErrorMessage('Class: Class_Zone; Function: getBibById' . NL . $e->getMessage());
          return $this->_dataBaseError;
        }
  }

510

511 512 513 514 515 516
  public function getFilePath() {
    return ($this->getFileName() == $this->getFile()) ?
      $this->getBasePath().$this->getFile() : $this->getFile();
  }


517
  public function getFile() {
518 519 520
    return $this->getPhoto();
  }

Laurent's avatar
Laurent committed
521

Laurent's avatar
Laurent committed
522
  public function getThumbnailPath() {
523
    return $this->getBasePath() . self::THUMB_PREFIX . $this->getFile();
524
  }
525 526


Laurent's avatar
Laurent committed
527
  public function getBase($prefix) {
528
    return str_replace('//', '/',
529
                       $prefix.'/'.self::BASE_PATH.'/');
530 531 532
  }


533 534 535
  public function getAllStatus() {
    return $this->statut_bib;
    $status= [];
Patrick Barroca's avatar
Patrick Barroca committed
536
    foreach ($this->statut_bib as $statut)
537 538
      $status[$statut]=$statut;
    return $status;
Patrick Barroca's avatar
Patrick Barroca committed
539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
  }


  // crée un dictionnaire depuis un liste d'enregistrements.
  // la clé est la valeur du champ id_field
  private function rowsToDict(&$rows, $id_field) {
    $dict = array();
    foreach ($rows as $row) {
      $key = $row[$id_field];
      $dict[$key] = $row;
    }
    return $dict;
  }


  // crée un dictionnaire depuis un liste d'enregistrements.
  // la clé est la valeur du champ id_field
  // Chaque clé est associé à un array d'enregistrements correspondant
  private function groupRowsBy(&$rows, $id_field) {
    $dict = array();
    foreach ($rows as $row) {
      $key = $row[$id_field];
      if (!array_key_exists($key, $dict)) $dict[$key] = array();
      $dict[$key] []= $row;
    }
    return $dict;
  }

Laurent's avatar
Laurent committed
567

Patrick Barroca's avatar
Patrick Barroca committed
568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669
  private function treeConfig($type) {
    // liste des tables, classes, ... pour chaque type de données
    $configs = array(
                     'rss' => array(
                                    'cat_class' => 'Class_RssModelCategorie',
                                    'item_class' => 'Class_RssModelFlux',
                                    'cat_table' => 'rss_categorie',
                                    'item_table' => 'rss_flux',
                                    'cat_id_field' => 'ID_CAT',
                                    'item_id_field' => 'ID_RSS',
                                    'cat_parent_id_field' => 'ID_CAT_MERE',
                                    'require' => 'Rss.php'),
                     'sito' => array(
                                     'cat_class' => 'Class_SitothequeModelCategorie',
                                     'item_class' => 'Class_SitothequeModelSite',
                                     'cat_table' => 'sito_categorie',
                                     'item_table' => 'sito_url',
                                     'cat_id_field' => 'ID_CAT',
                                     'item_id_field' => 'ID_SITO',
                                     'cat_parent_id_field' => 'ID_CAT_MERE',
                                     'require' => 'Sitotheque.php')
    );
    return $configs[$type];
  }


  private function getCategoriesForBibAndTable($id_bib, $cat_table) {
    $cat_where_clause = $id_bib==0 ? '' : ' WHERE ID_SITE='.$id_bib;
    $categories = fetchAll('SELECT  ID_SITE, ID_CAT,ID_CAT_MERE, LIBELLE '.
                           'FROM '.$cat_table.
                           $cat_where_clause.
                           ' ORDER BY LIBELLE');
    if ($categories==false) $categories = array();
    return $categories;
  }

  /*
    Retourne la liste des arborescences bibliothèques / catégories / articles qui ont des articles visibles
    Utilisé pour construire le JSON envoyer au widget jquery TreeSelect.
    * type = sito | rss
    * id_bib : l'id de la bib, 0 signifie toutes les bibliothèques
    * do_load_items: si true, les items (articles, flux ou sites) ne seront chargés (sinon seulement les catégories).
    */
  public function buildBibTree($id_bib, $type, $do_load_items){
    //LL: TODO quand j'aurai le courage, faire une class de base pour les RSS/Sito/CMS et mettre en
    // place du Strategy pour supprimer toutes les duplications de code

    //va chercher les tables, classes, noms de champs utilisés
    $config = $this->treeConfig($type);
    require_once($config['require']);

    //en mode portail on doit afficher toutes les bibliothèques
    $is_portail = ($id_bib==0);

    $bibs = $this->getBibsBySite($id_bib);
    if ($is_portail) $bibs []= array('ID_SITE' => 0, 'LIBELLE' => 'Portail');
    //on indexe les bib par identifiant pour pouvoir retrouver la bib. de l'item (article, rss, sito) par la suite
    $bibs = $this->rowsToDict($bibs, 'ID_SITE');

    //recherche les catégories puis indexation pour retrouver toutes les catégories d'une bib
    //(Tout ça pour éviter de faire plusieurs requêtes à la base de données)
    $categories = $this->getCategoriesForBibAndTable($id_bib, $config['cat_table']);
    $cat_by_bib = $this->groupRowsBy($categories, 'ID_SITE');
    $categories = $this->rowsToDict($categories, $config['cat_id_field']);


    //Recherche des items par rapport à toutes les catégories trouvées si nécessaire
    if ((count($categories) > 0) and $do_load_items) {
      $where_clause = 'WHERE '.$config['cat_id_field'].' IN('.implode(',', array_keys($categories)).')';
      //si on est sur le CMS, filtre pour ne prendre que les articles avec date de publication valide

      $items = fetchAll('SELECT '.$config['cat_id_field'].', '.$config['item_id_field'].', TITRE'.
                        ' FROM '.$config['item_table'].' '.
                        $where_clause.
                        ' ORDER BY '.$config['cat_id_field'].', TITRE');
      if ($items==false) $items = array();
      $items_by_cat = $this->groupRowsBy($items, $config['cat_id_field']);
    }

    //on a les bibs, catégories et items, on construit les arbres pour chaque bib
    $bib_trees = array();
    foreach ($bibs as $bib) {
      $builder = new CompositeBuilder($config['cat_class'], $config['item_class']);
      $categories = $cat_by_bib[$bib['ID_SITE']];
      if (!$categories && $is_portail) continue;

      $builder->getRoot()->addCategoriesFromRows($categories, $config['cat_id_field'], $config['cat_parent_id_field']);

      foreach($categories as $cat) {
        $items = $items_by_cat[$cat['ID_CAT']];
        if ($items)
          $builder->getRoot()->addItemsFromRows($items, $config['item_id_field'], $config['cat_id_field']);
      }

      $bib_cat = new ItemCategory($bib["ID_SITE"]);
      $bib_cat->setLabel($bib["LIBELLE"]);
      $bib_cat->addAllCategories($builder->getRoot()->getCategories());
      $bib_trees []= $bib_cat;
    }

    return $bib_trees;
  }
llaffont's avatar
llaffont committed
670 671


Laurent's avatar
Laurent committed
672
  public function afterSave() {
673 674 675
    $this->isSIGBSendData()
      ? $this->ensureIntBib()
      : $this->deleteIntBibRelated();
Patrick Barroca's avatar
Patrick Barroca committed
676 677 678
  }


Laurent's avatar
Laurent committed
679 680 681 682 683
  public function getLabel() {
    return $this->getLibelle();
  }


Patrick Barroca's avatar
Patrick Barroca committed
684 685 686 687 688 689 690 691 692 693 694 695 696 697
  public function articlesToJSON($include_items = true) {
    $json_categories = [];
    $categories = $this->getArticleCategories();
    foreach($categories as $cat)
      $json_categories []= $cat->toJSON($include_items);

    return  '{'.
      '"id":'.$this->getId().','.
      '"label": "'.htmlspecialchars(trim($this->getLibelle())).'",'.
      '"categories": ['.implode(",", $json_categories).'],'.
      '"items": []}';
  }


698 699 700 701 702 703
  public function getRecursiveArticleCategories() {
    $categories=[];
    foreach($this->getArticleCategories() as $cat) {
      $categories[]=$cat;
      $categories= array_merge($categories,$cat->getRecursiveSousCategories());
    }
efalcy's avatar
efalcy committed
704
    return $categories;
705
  }
Patrick Barroca's avatar
Patrick Barroca committed
706

efalcy's avatar
efalcy committed
707

Patrick Barroca's avatar
Patrick Barroca committed
708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725
  public function getArticleCategoriesToJson() {
    return $this->articlesToJSON(false);
  }


  /** @see Trait_PermissionTargetable */
  public function getPermissionsEditUrl($view) {
    return $view->url(['module' => 'admin',
                       'controller' => 'bib',
                       'action' => 'permissions',
                       'id' => (int)$this->getId()], null, true);
  }


  /** @see Trait_PermissionTargetable */
  public function getPermissionsChildren() {
    return $this->getArticleCategories();
  }
Patrick Barroca's avatar
Patrick Barroca committed
726 727 728 729 730


  public function getRedmineLoginOrKey() {
    return ($login = $this->getRedmineLogin()) ? $login : $this->getRedmineApiKey();
  }
731

Laurent's avatar
Laurent committed
732

733 734 735
  public function isReceivedFile() {
    if (!$this->_isFileInRequest('photo'))
      return true;
736 737 738 739

    if ($this->_file_uploaded)
      return $this->_file_uploaded;
    return $this->_file_uploaded = $this->receiveFile();
740 741
  }

Laurent's avatar
Laurent committed
742

743
  protected function _isFileInRequest($name) {
744
    return array_key_exists($name, $_FILES);
745
  }
746

Laurent's avatar
Laurent committed
747

748 749 750 751
  public static function setDefaultImageFactory($factory) {
    static::$_default_image_factory = $factory;
  }

Laurent's avatar
Laurent committed
752

753 754 755 756
  public static function getImageFactory($file) {
    return isset(static::$_default_image_factory)
      ? static::$_default_image_factory
      : new Imagick($file);
757 758
  }

759

760
  public function validate() {
Laurent's avatar
Laurent committed
761 762
    $this->checkAttribute('photo',
                          $this->isReceivedFile('photo'),
763
                          implode(',', array_unique($this->getErrors())));
764 765 766 767 768 769 770 771


    $validator = new ZendAfi_Validate_RewriteUrl();
    $validator->isValid($this);
    foreach($validator->getMessages() as $message) {
      $this->checkAttribute('rewrite_url', false, $message);
    }

772
  }
773

Laurent's avatar
Laurent committed
774

775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791
  public function receiveFile() {
    $oldFile = $this->getPhoto();
    $filename = ($this->getFileName());
    $path = ($filename==$oldFile) ?
      $this->getBasePath().$oldFile : $oldFile;

    $to_delete = [$path, $this->getBasePath().'thumb_'.$filename];
    $on_update = function($old_file, $new_file) use ($to_delete) {
      if ($old_file && $old_file != $new_file)
        foreach($to_delete as $item)
          $this->getFileSystem()->unlink($item);

      $this->createThumbnail();

      return true;
    };

792
    $handler = $this->getUploadHandler('photo', static::UPLOAD_MAX_SIZE)
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
                    ->setAllowedExtensions(['jpg', 'gif', 'png', 'jpeg']);

    return (new Class_FileProperty($this, 'photo', $handler, $on_update))
      ->receive();
  }


  public function createThumbnail() {
    if ('' == $this->getFile())
      return true;

    try {
      $image = self::getImageFactory($this->getBasePath() . $this->getFile());
      $image->thumbnailImage(160, 0);

      if (!$image->writeImage($this->getThumbnailPath())) {
        $this->addError('Erreur lors de l\'enregistrement de la vignette');
        return false;
      }

      return true;

    } catch (Exception $e) {
      $this->addError('Erreur lors de la création de la vignette '
                      . (string)$e->getMessage());
      return false;
    }
  }

Laurent's avatar
Laurent committed
822

823 824 825 826
  public function getFileName() {
    $path=explode('/',$this->getFile());
    return end($path);
  }
Laurent's avatar
Laurent committed
827 828


829 830 831 832
  public  function getBasePath() {
    return $this->getBase(USERFILESPATH);
  }

Laurent's avatar
Laurent committed
833

834
  public function getUploadHandler($name,$limit_size_in_ko=-1) {
835 836 837
    if (null === $this->_uploadHandler) {
      $this->_uploadHandler = Class_Upload::newInstanceFor($name)
        ->setBaseName($this->getId())
838 839
        ->setBasePath($this->getBasePath())
        ->setMaxSize($limit_size_in_ko);
840 841 842 843 844 845 846
    }

    return $this->_uploadHandler;
  }


  public function setUploadMover($name, $mover) {
847
    $this->getUploadHandler($name,static::UPLOAD_MAX_SIZE)->setUploadMover($mover);
848 849 850 851
    return $this;
  }


852
  public function getFacet() {
853
    return Class_Bib::CODE_FACETTE . $this->getIdSite();
854 855 856 857
  }


  public function getFacetLabel() {
858 859
    return $this->getIntBib()
      ? $this->getIntBib()->getNomCourt()
860 861
      : $this->getLibelle();
  }
Ghislain Loas's avatar
Ghislain Loas committed
862 863


864 865 866
  public function includeItem($item) {
    return $this->getId() == $item->getIdBib();
  }
Ghislain Loas's avatar
Ghislain Loas committed
867 868


869
  public function getOuvertureOnDate($time) {
870 871 872
    if($this->hasHoraire())
      return null;

873 874 875 876 877 878 879 880
    if ($ouverture = Class_Ouverture::findFirstBy(['jour' => date('Y-m-d', $time),
                                                   'id_site' => $this->getId()]))
      return $ouverture;

    if ($this->isClosedOnHolidays() && Class_Date_Holiday::isHoliday($time))
      return null;

    $day_of_week = Class_Date::dayOfWeek($time);
881 882 883 884 885 886 887 888 889 890 891 892 893 894 895
    $openings = new Storm_Model_Collection($this->getOuvertures());

    $blessed = $openings->select('hasValidityRange')
                        ->detect(
                                 function($o) use ($time, $day_of_week) {
                                   return $o->isValidOnDate($time) && ($o->getJourSemaine() == $day_of_week);
                                 });

    return $blessed
      ? $blessed
      : $openings->reject('hasValidityRange')
                 ->detect(
                          function($o) use ($day_of_week) {
                            return $o->getJourSemaine() == $day_of_week;
                          });
896 897 898 899 900 901
  }


  public function isOpened() {
    return null !== $this->getOuvertureOnDate($this->getCurrentTime());
  }
902 903


904 905 906 907
  public function isOpenedNow() {
    if (!$ouverture = $this->getOuvertureOnDate($this->getCurrentTime()))
      return false;

908 909 910
    return Class_Ouverture_State::from($ouverture)
      ->onIsOpenedUntil(true)
      ->evaluateAt($this->getCurrentTime());
911 912 913
  }


914
  public function getZoneLibelle() {
915 916 917 918 919 920 921
    return ($zone = $this->getZone())
      ? $zone->getLibelle()
      : '';
  }


  public function acceptOpeningsVisitor($visitor) {
Patrick Barroca's avatar
Patrick Barroca committed
922
    $visitor->visitSimple($this->getHoraire());
923 924 925 926 927

    foreach($this->getOuvertures() as $opening)
      $visitor->visitOpening($opening);

    return $this;
928
  }
929 930 931 932 933 934 935 936 937 938 939 940 941 942


  public function getLatitude() {
    return $this->hasLieu()
      ? $this->getLieu()->getLatitude()
      : null;
  }


  public function getLongitude() {
    return $this->hasLieu()
      ? $this->getLieu()->getLongitude()
      : null;
  }
llaffont's avatar
llaffont committed
943
}