CodifThesaurus.php 25.5 KB
Newer Older
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
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
Alex Arnaud's avatar
Alex Arnaud committed
19
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA
20 21
 */

Ghislain Loas's avatar
Ghislain Loas committed
22 23 24
class CodifThesaurusLoader extends Storm_Model_Loader {
  use Trait_Translator;

25 26 27 28 29 30 31
  const
    SUGGEST_HIERARCHY_CONTAINS = 1,
    SUGGEST_LABEL_STARTS_WITH = 2,
    SUGGEST_LABEL_CONTAINS = 3,
    SUGGEST_INDEX_STARTS_WITH = 4;


32
  protected
33 34
    $_fixed = [],
    $_customfields_facet_prefix;
35 36 37 38 39 40

  public function __construct($class) {
    parent::__construct($class);
    $this->_fixed = Class_CodifThesaurusFixed::getAll();
  }

Ghislain Loas's avatar
Ghislain Loas committed
41

42 43 44 45 46 47 48
  public function findFixed($key) {
    return isset($this->_fixed[$key])
      ? $this->_fixed[$key]
      : null;
  }


Patrick Barroca's avatar
Patrick Barroca committed
49
  public function findThesaurusForCatalogue($catalogue_id) {
50 51
    return Class_CodifThesaurus::getLoader()
      ->findFirstBy(['id_origine'=> $catalogue_id,
52 53 54 55 56 57 58 59 60
                     'code' => Class_CodifThesaurus::fixedCodeOf('Domain')]);
  }


  public function collectForModelsUnderFixed($fixed_name, $models, $closure) {
    if (!isset($this->_fixed[$fixed_name]))
      return;

    foreach($models as $model)
61
      $closure($this->ensureForModelUnderRoot($model, $this->_fixed[$fixed_name]));
62 63 64
  }


65
  public function findLibraryNoveltyFor($library_id) {
66 67 68 69 70 71
    return ($library = Class_Bib::find((int)$library_id))
      ? $this->_ensureLibraryNoveltyThesaurus($library)
      : null;
  }


72
  public function ensureForModelUnderRoot($model, $definition) {
73 74 75 76
    return ($root = Class_CodifThesaurus::findRootOfId($definition->getId(),
                                                       $definition->getCode(),
                                                       $definition->getLabel()))
      ? $root->getOrCreateChild($model->getId(), $model->getLibelle())
77
      : null;
78 79 80
  }


81
  protected function _ensureLibraryNoveltyThesaurus($model) {
82
    return $this->ensureForModelUnderRoot($model, $this->_fixed['LibraryNovelty']);
83 84 85 86
  }


  protected function _ensureAnnexeNoveltyThesaurus($model) {
87
    return $this->ensureForModelUnderRoot($model, $this->_fixed['AnnexeNovelty']);
88 89 90
  }


91
  public function findForCustomField($field) {
92 93 94 95 96 97 98 99 100 101
    return Class_CodifThesaurus::findForCustomFieldMeta($field->getMeta());
  }


  public function getOrCreateForCustomField($field) {
    return Class_CodifThesaurus::getOrCreateForCustomFieldMeta($field->getMeta());
  }


  public function findForCustomFieldMeta($meta) {
102
    return Class_CodifThesaurus::getLoader()
103
      ->findFirstBy(['id_origine' => $meta->getId(),
104
                     'code' => Class_CodifThesaurus::fixedCodeOf('CustomField')]);
105 106 107
  }


108 109
  public function getOrCreateForCustomFieldMeta($meta) {
    return Class_CodifThesaurus::findCustomFieldsRoot()
110
      ->getOrCreateChild($meta->getId(), $meta->getLabel());
111 112 113
  }


114
  public function findCustomFieldsRoot() {
115 116 117 118 119
    $definition = $this->_fixed['CustomField'];
    return Class_CodifThesaurus::findRootOfId($definition->getId(),
                                              $definition->getCode(),
                                              $definition->getLabel());
  }
120

Ghislain Loas's avatar
Ghislain Loas committed
121

122 123 124
  public function findForItemLibraryNovelty($item) {
    if(!$library = $item->getBib())
      return null;
125

126
    return ($item = $this->ensureForModelUnderRoot($library, $this->_fixed['LibraryNovelty']))
127 128
      ? $item->getFacetteIndex()
      : '';
Patrick Barroca's avatar
Patrick Barroca committed
129 130 131
  }


132 133
  public function findForItemAnnexeNovelty($item) {
    if(!$model = $item->getCodifAnnexe())
Ghislain Loas's avatar
Ghislain Loas committed
134 135
      return null;

136
    return ($item = $this->ensureForModelUnderRoot($model, $this->_fixed['AnnexeNovelty']))
137 138
      ? $item->getFacetteIndex()
      : '';
Ghislain Loas's avatar
Ghislain Loas committed
139 140 141
  }


142
  public function countChildrenOf($id_thesaurus) {
Ghislain Loas's avatar
Ghislain Loas committed
143 144 145
    $where = sprintf('id_thesaurus like "%s%%" and LENGTH(id_thesaurus) > %s',
                     $id_thesaurus,
                     strlen($id_thesaurus));
146

Ghislain Loas's avatar
Ghislain Loas committed
147 148 149 150
    return  Class_CodifThesaurus::countBy(['where' => $where]);
  }


151
  public function findChildrenOfWith($id_thesaurus, $limit, $order) {
Ghislain Loas's avatar
Ghislain Loas committed
152 153 154 155 156
    $where = sprintf('id_thesaurus like "%s%%" and LENGTH(id_thesaurus) = %s',
                     $id_thesaurus,
                     (strlen($id_thesaurus) + 4));

    return Class_CodifThesaurus::findAllBy(['where' => $where,
157
                                            'limitPage' => $limit,
Ghislain Loas's avatar
Ghislain Loas committed
158
                                            'order' => $order]);
159 160 161
  }


162 163
  public function findRootOfId($id, $code, $label) {
    if ($codif = Class_CodifThesaurus::findFirstBy(['id_thesaurus' => $id]))
Ghislain Loas's avatar
Ghislain Loas committed
164 165
      return $codif;

166 167 168
    $attributes = ['id_thesaurus' => $id,
                   'libelle' => $label,
                   'code' => $code];
Ghislain Loas's avatar
Ghislain Loas committed
169 170

    $codif = Class_CodifThesaurus::newInstance($attributes);
171 172

    return $codif->save() ? $codif : null;
Ghislain Loas's avatar
Ghislain Loas committed
173 174 175
  }


Patrick Barroca's avatar
Patrick Barroca committed
176
  public function addFacetForSigb($facet_name, $facet_rules, $comm_sigb) {
177 178 179 180 181 182 183 184 185 186 187 188 189 190
    if (!Class_IntBib::findFirstBy(['comm_sigb' => $comm_sigb]))
      return;

    $parts = explode('$', trim($facet_rules));
    if (2 !== count($parts))
      return;

    $zone = $parts[0];
    $label_field = $parts[1];
    $rules = (new Class_CodifThesaurus_Rules())
      ->setZone($zone)
      ->setLabelField($label_field);

    if (Class_CodifThesaurus::findFirstBy(['rules' => $rules->format()]))
Patrick Barroca's avatar
Patrick Barroca committed
191
      return ;
192 193 194 195 196 197

    Class_CodifThesaurus::newInstance(['libelle'          => $facet_name,
                                       'libelle_facette'  => $facet_name,
                                       'rule_zone'        => $zone,
                                       'rule_label_field' => $label_field])
      ->save();
Patrick Barroca's avatar
Patrick Barroca committed
198 199 200 201 202 203
  }


  public function getLibelleHierarchique($enreg) {
    if (!$enreg)
      return '';
204 205

    if (!$parent = Class_CodifThesaurus::findParent($enreg->getIdThesaurus()))
Patrick Barroca's avatar
Patrick Barroca committed
206 207
      return $enreg->getLibelle();

208 209
    if (strlen($parent->getIdThesaurus()) <= 8)
      return $parent->getLibelle() . ' : ' . $enreg->getLibelle();
Patrick Barroca's avatar
Patrick Barroca committed
210

211
    return $this->getLibelleHierarchique($parent) . ' : ' . $enreg->getLibelle();
Patrick Barroca's avatar
Patrick Barroca committed
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
  }


  public function findParent($id_thesaurus) {
    $parent_str=substr($id_thesaurus,0,strlen($id_thesaurus)-(4-strlen($id_thesaurus)%4));
    if (!$parent_str)
      return null;

    $parent = Class_CodifThesaurus::findFirstBy(['where' => 'id_thesaurus like "'.$parent_str.'%" and LENGTH(id_thesaurus)<'.strlen($id_thesaurus),
                                                 'order' => 'id_thesaurus desc']);
    if (!$parent)
      return $this->findParent($parent_str);

    return $parent;
  }


  /** @return string */
  public function findNextThesaurusChildId($code, $parentid_thesaurus) {
    Class_CodifThesaurus::clearCache();
    $last_thesaurus = Class_CodifThesaurus::findFirstBy(['code' => $code,
                                                         'where' => 'id_thesaurus like "'.$parentid_thesaurus.'%"',
                                                         'order' => 'id_thesaurus desc']);
    if (!$last_thesaurus)
      return $parentid_thesaurus.'0001';
237

Patrick Barroca's avatar
Patrick Barroca committed
238 239
    if (strlen($parentid_thesaurus) >=strlen($last_thesaurus->getIdThesaurus()))
      return $parentid_thesaurus.'0001';
240

Patrick Barroca's avatar
Patrick Barroca committed
241 242 243 244 245
    return $this->incrementId(substr($last_thesaurus->getIdThesaurus(),0, strlen($parentid_thesaurus)+4)) ;
  }


  public function incrementId($id) {
246
    $last=base_convert(substr($id,strlen($id)-4), 36, 10);
Patrick Barroca's avatar
Patrick Barroca committed
247 248
    $first_part=substr($id,0,strlen($id)-4);
    $last++;
249
    $last = strtoupper(base_convert($last, 10, 36));
Patrick Barroca's avatar
Patrick Barroca committed
250 251 252 253 254 255
    return $first_part.$this->getCodeSur4Chiffres($last,true);
  }


  public function findNextRacineCatalogue() {
    $last_thesaurus = Class_CodifThesaurus::findFirstBy(['where' => 'code like "catalogue" and LENGTH(id_thesaurus) in (1,8)',
256
                                                         'order' => 'id_thesaurus desc']);
Patrick Barroca's avatar
Patrick Barroca committed
257

258 259 260
    return $last_thesaurus
      ? $this->incrementId($last_thesaurus->getIdThesaurus())
      : Class_CodifThesaurus::fixedIdOf('Domain') . '0001';
Patrick Barroca's avatar
Patrick Barroca committed
261 262 263
  }


264 265 266 267 268 269 270 271 272 273 274
  public function deleteAllWithIdOrigineAndCode($id_origine, $code_thesaurus) {
    foreach (Class_CodifThesaurus::findAllBy(['id_origine' => $id_origine,
                                              'code' => $code_thesaurus ])
             as $thesaurus)
      Class_CodifThesaurus::deleteAllFrom($thesaurus);
  }


  public function deleteAllFrom($thesaurus) {
    if ($thesaurus && '' != $thesaurus->getIdThesaurus())
      sqlExecute('delete from codif_thesaurus where id_thesaurus like "' . $thesaurus->getIdThesaurus() . '%"');
Patrick Barroca's avatar
Patrick Barroca committed
275 276 277 278 279 280 281
  }


  /**
   * @param int
   * $return Class_CodifThesaurus
   */
282 283 284
  public function findByIdOrigineAndCode($id_origine, $code_thesaurus) {
    return Class_CodifThesaurus::findFirstBy(['id_origine' => $id_origine,
                                              'code' => $code_thesaurus ]);
Patrick Barroca's avatar
Patrick Barroca committed
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
  }


  public static function getCodeSur4Chiffres($code,$before=false) {
    $length=strlen($code);
    while (strlen($code) %4 != 0)  {
      if ($before)
        $code = '0'.$code;
      else
        $code .='0';
    }
    return $code;
  }


300
  public function getIndices($pere, $all = false ) {
301 302 303
    if(Class_CodifThesaurus::CODE_ROOT != $pere) {
      $pere = $this->getCodeSur4Chiffres($pere);
      $length = strlen($pere);
304

305 306
      return Class_CodifThesaurus::findAllBy(['where' => 'id_thesaurus like "'.$pere.'%" and LENGTH(id_thesaurus) in ('.($length+1).','.($length+4).')',
                                              'order'=> 'id_thesaurus']);
Patrick Barroca's avatar
Patrick Barroca committed
307 308
    }

309
    $where = '';
310

311 312 313
    // while search result do not handle item novelty correctly
    $to_exclude = [$this->fixedCodeOf('LibraryNovelty'),
                   $this->fixedCodeOf('AnnexeNovelty')];
314
    if (!$all)
315 316 317
      $to_exclude[] = $this->fixedCodeOf('Domain');

    $where = sprintf('code not in ("%s") and ', implode('", "', $to_exclude));
318

319
    $where .= 'LENGTH(id_thesaurus) in (1,4)';
320 321

    return Class_CodifThesaurus::findAllBy(['where' => $where,
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
                                            'order' => 'id_thesaurus']);
  }


  public function fixedCodeOf($name) {
    return isset($this->_fixed[$name]) ? $this->_fixed[$name]->getCode() : '';
  }


  public function fixedIdOf($name) {
    return isset($this->_fixed[$name]) ? $this->_fixed[$name]->getId() : '';
  }


  public function fixedLabelOf($name) {
    return isset($this->_fixed[$name]) ? $this->_fixed[$name]->getLabel() : '';
Patrick Barroca's avatar
Patrick Barroca committed
338 339 340 341
  }


  public function getFacettesIndex() {
342
    return array_map(function($item) { return $item->getFacetteIndex(); },
343 344 345 346 347 348
                     Class_CodifThesaurus::getFacettesThesauri());
  }


  public function getFacettesThesauri() {
    $filter = function($item) {
349
      return Class_CodifThesaurus::fixedIdOf('CustomField') != $item->getIdThesaurus();
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
    };

    $thesauri = array_filter(Class_CodifThesaurus::getIndices('root', true), $filter);

    foreach(Class_CodifThesaurus::findCustomFieldsRoot()->getChildren() as $item)
      $thesauri[] = $item;

    return $thesauri;
  }


  public function findChildrenOf($parent) {
    if (!$parent || !$id_thesaurus = $parent->getIdThesaurus())
      return [];

    $where = sprintf('id_thesaurus like "%s%%" and LENGTH(id_thesaurus) = %s',
                     $id_thesaurus, strlen($id_thesaurus) + 4);

    return Class_CodifThesaurus::findAllBy(['where' => $where,
                                            'order' => 'libelle']);
Patrick Barroca's avatar
Patrick Barroca committed
370
  }
371 372 373


  public function getFacetGroup($facet) {
Patrick Barroca's avatar
Patrick Barroca committed
374
    return substr($facet, 0, $this->isCustomFieldsFacet($facet) ? 9 : 5);
375 376 377 378 379 380 381 382 383 384 385 386 387 388
  }


  protected function isCustomFieldsFacet($facet) {
    return $this->startsWith($facet, $this->getCustomFieldsFacetPrefix());
  }


  protected function startsWith($value, $prefix) {
    return $prefix == substr($value, 0, strlen($prefix));
  }


  protected function getCustomFieldsFacetPrefix() {
389 390 391
    if (!isset($this->_customfields_facet_prefix))
        return $this->_customfields_facet_prefix = Class_CodifThesaurus::CODE_FACETTE . Class_CodifThesaurus::fixedIdOf('CustomField');
    return $this->_customfields_facet_prefix;
392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 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 445 446 447 448 449 450 451 452 453 454 455 456 457
  }


  public function suggestFrom($recherche, $mode, $limite_resultat, $theme) {
    if (!$req = $this->_suggestQueryFor((int)$mode, $theme, $recherche, $limite_resultat))
      return [];

    $resultat=fetchAll($req);

    if (!$resultat)
      return [];

    foreach($resultat as $enreg) {
      $thesaurus = Class_CodifThesaurus::find($enreg["id"]);
      $libelle = Class_CodifThesaurus::getLibelleHierarchique($thesaurus);
      $liste[] = [$enreg["id_thesaurus"],
                  $enreg["id_origine"]." : ".$libelle];
    }

    return $liste;
  }


  protected function _suggestQueryFor($mode, $parent, $term, $limit) {
    $parent_clause = $this->_fieldStartsWith('id_thesaurus', $parent);

    if (static::SUGGEST_HIERARCHY_CONTAINS == $mode) {
      return (3 <= strlen($term))
        ? $this->_orderAndLimit("select distinct(id), id, id_thesaurus, id_origine "
                                ."from codif_thesaurus where id_thesaurus regexp (select group_concat(concat(id_thesaurus,'.*') separator '|') from codif_thesaurus where ". $parent_clause ." and id_origine is not null and " . $this->_fieldContains('libelle', $term) . ")",
                                $limit)
        : null;
    }

    $basic_select = "select id, id_thesaurus, id_origine from codif_thesaurus where ". $parent_clause;
    if (static::SUGGEST_LABEL_STARTS_WITH == $mode)
      return $this->_orderAndLimit($basic_select . ' and ' . $this->_fieldStartsWith('libelle', $term),
                                   $limit);

    if (static::SUGGEST_LABEL_CONTAINS == $mode)
      return $this->_orderAndLimit($basic_select . ' and ' . $this->_fieldContains('libelle', $term),
                                   $limit);

    if (static::SUGGEST_INDEX_STARTS_WITH == $mode)
      return $this->_orderAndLimit($basic_select . ' and ' . $this->_fieldStartsWith('id_origine', $term),
                                   $limit);
  }


  protected function _orderAndLimit($sql, $limit) {
    return $sql . ' order by id_thesaurus limit ' . $limit;
  }


  protected function _fieldStartsWith($field, $value) {
    return $this->_like($field, addslashes($value) . '%');
  }


  protected function _fieldContains($field, $value) {
    return $this->_like($field, '%' . addslashes($value) . '%');
  }


  protected function _like($field, $clause) {
    return $field . ' like \''. $clause . '\'';
458
  }
Ghislain Loas's avatar
Ghislain Loas committed
459 460 461 462 463 464 465 466 467 468 469 470


  public function getDynamicCodes() {
    $dynamic_facets = Class_CodifThesaurus::findAllBy(['rules not' => null,
                                                       'code not' => null,
                                                       'id_thesaurus not' => null]);
    $params = [];
    foreach($dynamic_facets as $facet)
      $params [] =  $facet->getCode();

    return array_unique($params);
  }
471 472 473 474 475


  public function root() {
    return Class_CodifThesaurus::newInstance();
  }
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505


  public function newIdThesaurusForLabel($label) {
    $id = substr(strtoupper($label), 0, Class_CodifThesaurus::ID_KEY_LENGTH);

    if (strlen($id) == Class_CodifThesaurus::ID_KEY_LENGTH
        && !Class_CodifThesaurus::findFirstBy(['id_thesaurus' => $id]))
      return $id;

    $label = substr(strtoupper($label), 0, 3);
    $suffixes = array_merge(range(0, 9), range('a', 'z'));

    while(!empty($suffixes)) {
      $suffix = strtoupper(array_shift($suffixes));
      $id = sprintf("%'".$suffix."-4s", $label);

      if (!Class_CodifThesaurus::findFirstBy(['id_thesaurus' => $id]))
        return $id;
    }
  }


  public function withDynamicFacetsHavingIdFieldDo($closure) {
    (new Storm_Model_Collection(Class_CodifThesaurus::findAllBy(['rules not' => null,
                                                                 'rules not' => '',
                                                                 'id_thesaurus not' => null,
                                                                 'order' => 'libelle'])))
      ->select('hasRuleIdField')
      ->eachDo($closure);
  }
506
}
llaffont's avatar
llaffont committed
507 508 509 510




511
class Class_CodifThesaurus extends Storm_Model_Abstract {
512
  use Trait_Translator, Trait_MemoryCleaner, Trait_Facetable, Trait_TreeNode;
Patrick Barroca's avatar
Patrick Barroca committed
513

514
  const
515 516
    CODE_ROOT = 'root',

517
    COLUMN_ORIGIN_SIZE = 20,
518
    ID_KEY_LENGTH = 4,
519

520
    CODE_FACETTE = 'H';
521

Ghislain Loas's avatar
Ghislain Loas committed
522
  protected $_loader_class = 'CodifThesaurusLoader';
523
  protected $_table_name = 'codif_thesaurus';
524
  protected $_table_primary = 'id';
525 526
  protected $_default_attribute_values = ['libelle' => '',
                                          'libelle_facette' => '',
527
                                          'id_thesaurus' => null,
528
                                          'id_origine' => null,
Ghislain Loas's avatar
Ghislain Loas committed
529 530
                                          'rules' => null,
                                          'code' => null];
531

532 533 534 535 536 537 538 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 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585
  protected $_rules;


  public function __construct() {
    parent::__construct();
    $this->_rules = new Class_CodifThesaurus_Rules();
  }


  public function initializeAttributes($datas) {
    parent::initializeAttributes($datas);
    $this->_rules->initialize($this->getRules());
    return $this;
  }


  public function beforeSave() {
    $this->setRules($this->_rules->format());
  }


  public function getRuleZone() {
    return $this->_rules->getZone();
  }


  public function setRuleZone($zone) {
    $this->_rules->setZone($zone);
    return $this;
  }


  public function getRuleLabelField() {
    return $this->_rules->getLabelField();
  }


  public function setRuleLabelField($field) {
    $this->_rules->setLabelField($field);
    return $this;
  }


  public function getRuleIdField() {
    return $this->_rules->getIdField();
  }


  public function setRuleIdField($field) {
    $this->_rules->setIdField($field);
    return $this;
  }


586 587 588 589 590 591
  public function setRuleLabelStartPos($value) {
    $this->_rules->setLabelStartPos($value);
    return $this;
  }


592 593 594 595 596 597 598 599 600 601 602 603 604
  public function setRuleFilterField($field) {
    $this->_rules->setFilterField($field);
    return $this;
  }


  public function setRuleFilterValue($field) {
    $this->_rules->setFilterValue($field);
    return $this;
  }



605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625
  public function setRuleLabelLength($value) {
    $this->_rules->setLabelLength($value);
    return $this;
  }


  public function getRuleLabelLength() {
    return $this->_rules->getLabelLength();
  }


  public function getRuleLabelStartPos() {
    return $this->_rules->getLabelStartPos();
  }


  public function rulesTruncateLabels($labels) {
    return $this->_rules->truncateLabels($labels);
  }


626 627 628
  public function getRulesAsArray() {
    return ['rule_zone' => $this->_rules->getZone(),
            'rule_label_field' => $this->_rules->getLabelField(),
629 630
            'rule_id_field' => $this->_rules->getIdField(),
            'rule_label_start_pos' => $this->_rules->getLabelStartPos(),
631 632 633
            'rule_label_length' => $this->_rules->getLabelLength(),
            'rule_filter_field' => $this->_rules->getFilterField(),
            'rule_filter_value' => $this->_rules->getFilterValue()];
634 635 636 637 638 639 640 641
  }


  public function withLabelAndIdRulesDo($closure) {
    return $this->_rules->withLabelAndIdDo($closure);
  }


642 643
  public function getListeSuggestion($recherche, $mode, $limite_resultat, $theme) {
    return $this->getLoader()->suggestFrom($recherche, $mode, $limite_resultat, $theme);
Patrick Barroca's avatar
Patrick Barroca committed
644
  }
llaffont's avatar
llaffont committed
645

Alex Arnaud's avatar
Alex Arnaud committed
646

Patrick Barroca's avatar
Patrick Barroca committed
647
  public function getLibelleFacette() {
648 649
    return $this->_get('libelle_facette') && $this->_get('libelle_facette') != '' ?
      $this->_get('libelle_facette') : $this->getLibelle();
Patrick Barroca's avatar
Patrick Barroca committed
650
  }
651 652


653 654 655 656 657
  public function asFacet() {
    return $this->getFacetteIndex();
  }


Patrick Barroca's avatar
Patrick Barroca committed
658
  public function getFacetteIndex() {
659
    return self::CODE_FACETTE . $this->getIdThesaurus();
Patrick Barroca's avatar
Patrick Barroca committed
660
  }
Laurent's avatar
Laurent committed
661 662


Patrick Barroca's avatar
Patrick Barroca committed
663 664
  public function newChildEntry() {
    $code = $this->getCode();
Ghislain Loas's avatar
Ghislain Loas committed
665 666
    return Class_CodifThesaurus::getLoader()->newInstance(['code' => $code,
                                                           'id_thesaurus' => Class_CodifThesaurus::getLoader()->findNextThesaurusChildId(
667 668
                                                                                                                                         $code,
                                                                                                                                         $this->getIdThesaurus())]);
Patrick Barroca's avatar
Patrick Barroca committed
669
  }
Laurent's avatar
Laurent committed
670 671


Patrick Barroca's avatar
Patrick Barroca committed
672
  public function getOrCreateChild($id_origine, $label) {
673 674 675 676
    if (!$entry = $this->getChild($id_origine))
      $entry = $this->newChildEntry();

    if ($label == $entry->getLibelle())
677 678
      return $entry;

679 680
    $entry ->updateAttributes(['id_origine' => $id_origine,
                               'libelle' => $label]);
681

Patrick Barroca's avatar
Patrick Barroca committed
682
    return $entry->save() ? $entry : null;
Patrick Barroca's avatar
Patrick Barroca committed
683
  }
Laurent's avatar
Laurent committed
684 685


686 687 688 689 690 691 692 693 694
  public function getOrCreateChildren($labels) {
    return array_map(
                     function($label) {
                       return $this->getOrCreateChild(strtoupper($label), $label);
                     },
                     array_filter($labels));
  }


695 696 697 698 699 700 701 702 703 704
  public function getChild($id_origine) {
    return Class_CodifThesaurus::getLoader()
      ->findFirstBy(['code' => $this->getCode(),
                     'id_origine' => mb_substr($id_origine,
                                               0,
                                               self::COLUMN_ORIGIN_SIZE,
                                               'UTF-8')]);
  }


705 706 707 708 709 710 711 712 713 714 715
  public function withRulesDo($closure) {
    if ((!$this->_rules->getZone())
        || (!$this->_rules->getLabelField()))
      return;

    return $closure($this->_rules);
  }


  public function rulesCanHandle($reader)  {
    return $this->_rules->canHandle($reader);
Patrick Barroca's avatar
Patrick Barroca committed
716
  }
Laurent's avatar
Laurent committed
717

718

Patrick Barroca's avatar
Patrick Barroca committed
719
  public function validate() {
Patrick Barroca's avatar
Patrick Barroca committed
720 721 722
    $this->_validateIdThesaurus();

    $this->checkAttribute('libelle', '' != $this->getLibelle(), $this->_('Vous devez définir le libellé'));
Laurent's avatar
Laurent committed
723

724
    $this->check($this->_rules->isValid(), $this->_rules->getErrorMessage());
Patrick Barroca's avatar
Patrick Barroca committed
725
  }
726 727


Patrick Barroca's avatar
Patrick Barroca committed
728 729 730 731 732 733 734
  protected function _validateIdThesaurus() {
    $my_key = substr($this->getIdThesaurus(), -self::ID_KEY_LENGTH);
    $empty_key = str_repeat('0', self::ID_KEY_LENGTH);

    $this->checkAttribute('id_thesaurus',
                          $my_key != $empty_key,
                          $this->_('Nombre maximum d\'élément à ce niveau déjà atteint (%s)',
735
                                   str_repeat('Z', self::ID_KEY_LENGTH)));
Patrick Barroca's avatar
Patrick Barroca committed
736 737 738
  }


739
  public function deleteMeAndMyChildren() {
740
    $this->cleanRecords();
741
    $this->getLoader()->deleteAllFrom($this);
742 743 744 745
    return $this;
  }


746 747
  public function cleanRecords() {
    $facets = [];
Ghislain Loas's avatar
Ghislain Loas committed
748

749 750 751 752 753 754 755 756 757 758 759 760 761 762
    foreach($this->getLoader()->findChildrenOf($this) as $child)
      $facets[] = $child->getFacetteIndex();

    if (empty($facets))
      return $this;

    $facets = implode(' ', $facets);
    while ($records = Class_Notice::findAllBy(['where' => 'match(facettes) against(\'' . $facets . '\')',
                                               'limit' => 100])) {
      foreach($records as $record) {
        $record->deleteFacettes($facets)
               ->save();
      }

763
      $this->_cleanMemory();
764 765 766 767 768 769
    }

    return $this;
  }


770
  public function getOrCreateCustomFieldValueChild($value) {
771 772
    return $this->getOrCreateChild($this->getLoader()->fixedIdOf('CustomField') . hash('crc32b', $value),
                                   $value);
773 774 775
  }


776 777
  public function getChildren() {
    return $this->getLoader()->findChildrenOf($this);
778
  }
779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797


  public function getParentChildren() {
    return array_filter($this->getChildren(),
                        function ($children)
                        {
                          return ($children->hasChildren());
                        });
  }


  public function getChildrenItems() {
    return array_filter($this->getChildren(),
                        function ($children)
                        {
                          return (!$children->hasChildren());
                        });
  }

Ghislain Loas's avatar
Ghislain Loas committed
798

799 800 801 802
  public function getParent() {
    return $this->getLoader()->findParent($this->getIdThesaurus());
  }

803 804 805 806 807 808 809 810

  public function getParentId() {
    return $this->getParent()
      ? $this->getParent()->getId()
      : null;
  }


811 812 813 814
  public function getTitre() {
    return $this->getLibelleFacette();
  }

Ghislain Loas's avatar
Ghislain Loas committed
815

816 817 818
  public function numberOfChildrens() {
    return $this->getLoader()->countChildrenOf($this->getIdThesaurus());
  }
Ghislain Loas's avatar
Ghislain Loas committed
819 820 821 822 823


  public function isNotRoot() {
    return strlen($this->getIdThesaurus()) > Class_CodifThesaurus::ID_KEY_LENGTH;
  }
824 825


826 827 828 829 830 831 832 833 834 835 836 837 838
  public function getNodes() {
    if($this->isNew())
      return $this->getLoader()->getIndices('root', true);

    return $this->getParentChildren();
  }


  public function getLeaves($params) {
    if($this->isNew())
      return [];

    return $this->getLoader()->findChildrenOfWith($this->getIdThesaurus(),
839 840
                                                  $params['limitPage'],
                                                  $params['order']);
841 842 843 844 845 846 847 848 849 850 851 852
  }


  public function numberOfLeaves() {
    return count($this->getChildrenItems());
  }


  public function recursiveNumberOfChildren() {
    return $this->isNew()
      ? 0
      : $this->numberOfChildrens();
853
  }
854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875


  public function authoritiesIndexSystems() {
    if (!$this->getRuleIdField())
      return [];

    $systems = [];

    foreach(Class_IntProfilDonnees::findAllOfTypeAuthority() as $profile)
      $systems = $this->_addIndexSystemsFromPrefsInto($profile->getIndexSystemsPrefs(), $systems);

    return array_filter($systems);
  }


  protected function _addIndexSystemsFromPrefsInto($prefs, $systems) {
    foreach(Class_Notice_AuthorityIndexSystem::collectionFromPrefs($prefs)
            ->filterByThesaurus($this) as $system)
      $systems[] = $system;

    return $systems;
  }
876
}