PageRenderTime 185ms CodeModel.GetById 4ms app.highlight 166ms RepoModel.GetById 1ms app.codeStats 1ms

/class.xmoditea.inc

https://github.com/jcplat/console-seolan
PHP | 1551 lines | 1347 code | 61 blank | 143 comment | 255 complexity | 4f5a627689d8246c038f5d1a4935c678 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   1<?php
   2class XModItea extends XModTable {
   3  private $_cache;
   4  public $submodmax = 12;
   5  public $directsubdata;
   6  public $descrType;
   7  public $animauxok;
   8  public $restook;
   9  public $delparam = array();   // Parametres à passer au del sur import (pour empecher suppression des photo par ex) : cle => dpt, val => param
  10  public $prefix = 'ITEA_';
  11  public $exercice;    // Exercice en cours d'import
  12
  13  function __construct($ar = NULL) {
  14    parent::__construct($ar);
  15    $this->directsubdata = array(
  16        $this->prefix.'DETAILSOFREF' => array('situation', 'tourismeEtHandicap'),
  17        $this->prefix.'CONTACT' => array('siteWeb', 'languesParlees'),
  18        $this->prefix.'CHAMBRE' => array('description'),
  19        $this->prefix.'SUPPLEMENT' => array('description'));
  20    $this->directuniquesubdata=array(
  21        $this->prefix.'DETAILSOFREF' => array('descriptif' => 'description', 'descriptifTechnique' => 'description', 'descriptifCommercial' => 'description'));
  22    $this->descrType = array(
  23        'link' => array('INFO_TOUR', 'INFO_TOUR_ACTIV_OT', 'THEME', 'RUBRIQUE', 'RUBRIQUE_GENE'),
  24        //'no' => array('INFO_TOUR'),
  25        'tables' => array($this->prefix.'INFOTOUR', $this->prefix.'THEME', $this->prefix.'RUBRIQUE'),
  26        'fields' => array('theme' => 'theme', 'rubrique' => 'rubrique', 'rubrique_gene' => 'rubrique',
  27                          'info_tour_activ_ot' => 'info_tour_activ_ot', 'info_tour' => 'info_tour_activ_ot'),
  28        // champ => valeurs passées a analyseObject
  29        'cplt' => array('rubrique_gene' => array('general' => 1)),
  30        'notlink' => array(/*'rubrique_gene'*/)
  31        );
  32    $this->animauxok = $this->prefix.'CARACTERISTIQUE:O-40-';
  33    $this->restook = $this->prefix.'CARACTERISTIQUE:O-46-';
  34    XLabels::loadLabels('xmoditea');
  35  }
  36
  37  public function initOptions() {
  38    parent::initOptions();
  39    $this->_options->setOpt('Prefix', 'prefix', 'text');
  40    $this->_options->setOpt('Liste des départements (séparateur ,)', 'dpts', 'text');
  41    $p1 = XModule::findParam($this->_moid);
  42    $dpts = explode(', ', $p1['MPARAM']['dpts']);
  43    $conf = $GLOBALS['ITEACONF'][$p1['MPARAM']['table']];
  44    $this->_options->setOpt('Consolidation des caractéristiques','needconscaract','boolean',false,NULL);
  45    foreach ($dpts as $dpt) {
  46      if (!empty($dpt)) {
  47        $this->_options->setOpt($dpt.' : Adresse service SOAP',$dpt.'soap','text',NULL,$conf[$dpt]['soap']);
  48        $this->_options->setOpt($dpt.' : Adresse service SOAP XS (xsalto)',$dpt.'soap_xs','text',NULL,$conf[$dpt]['soap_xs']);
  49        $this->_options->setOpt($dpt.' : Environnement', $dpt.'env', 'text', NULL, $conf[$dpt]['env']);
  50        $this->_options->setOpt($dpt.' : Login', $dpt.'login', 'text', NULL, $conf[$dpt]['login']);
  51        $this->_options->setOpt($dpt.' : Password', $dpt.'pass', 'text', NULL, $conf[$dpt]['pass']);
  52        $this->_options->setOpt($dpt.' : Langues (tzr=>itea, séparateur ,)', $dpt.'langs', 'text', NULL, 'FR=>FRANCAIS');
  53      }
  54    }
  55  }
  56
  57  /// securite des fonctions accessibles par le web
  58  function secGroups($function, $group = NULL) {
  59    $g = array();
  60    $g['manuelImportFromITEA'] = array('admin');
  61    $g['importFromITEA'] = array('admin');
  62    $g['importDispoFromITEA'] = array('admin');
  63    $g['executeAllConsolidation'] = array('admin');
  64    $g['duplicateRubToRubGlob'] = array('admin');
  65    $g['importFromOtherBase'] = array('admin');
  66    $g['importDispoFromOtherBase'] = array('admin');
  67    if (isset($g[$function])) {
  68      if (!empty($group)) return in_array($group, $g[$function]);
  69      return $g[$function];
  70    }
  71    return parent::secGroups($function, $group);
  72  }
  73
  74  function _daemon($period = 'any') {
  75    // Vide le cache des requetes de dispo datant de plus de 2 heures
  76    updateQuery('delete from '.$this->prefix.'DISPOREQ where UPD<date_add(now(), interval -2 hour)');
  77    /// TODO: disparition des options
  78//     $dir=$GLOBALS['LIBTHEZORRO'].'contrib/itea/';
  79//     if ($period == 'daily') {
  80//       // Importe les champs afin de maintenir à jour le format des tables
  81//       $mod_ds = new XModDataSource();
  82//       $mod_ds->importFields(array('file'=>$dir.'fields.csv','prefixSQL'=>$this->prefix,'endofline'=>"\n"));
  83//       $mod_ds->importFields(array('file'=>$dir.'nomenclature_fields.csv','prefixSQL'=>$this->prefix,'endofline'=>"\n"));
  84//     }
  85  }
  86
  87  function insert($ar) {
  88    // En saisie manuelle, on fixe une date itea vieille pour ne pas gener un eventuel import
  89    $ar['options']['upditea']['value'] = '2000-01-01';
  90    return parent::insert($ar);
  91  }
  92
  93  function procInsert($ar = NULL) {
  94    // L'oid est forcé
  95    $p = new XParam($ar, NULL);
  96    $ref = $p->get('reference');
  97    $dpt = $p->get('dpt');
  98    $ar['newoid'] = $this->getOid($dpt, $ref);
  99    return parent::procInsert($ar);
 100  }
 101
 102  /// Retourne l'oid d'une reference dans un departement (le departement peut etre son numero ou son oid)
 103  function getOid($dpt, $ref) {
 104    $dpt = substr($dpt, -2);
 105    if (substr($ref, 0, 3) != $dpt.'_')
 106      return $this->table.':'.$dpt.'_'.rewriteToAscii(trim($ref), false);
 107    else
 108      return $this->table.':'.rewriteToAscii(trim($ref), false);
 109  }
 110
 111  /// Rend vrai si la table en question est utilisée dans le module en question
 112  public function usesTable($table) {
 113    return in_array($table, $this->allTables());
 114  }
 115
 116  /// Tables de nomenclature/communes
 117  public function nomenclatureTables() {
 118    return array(
 119        $this->prefix.'CHOIX_ON', $this->prefix.'TYPEPRODUIT', $this->prefix.'TYPEPIECE',
 120        $this->prefix.'TYPEGESTION', $this->prefix.'TYPELANGUE', $this->prefix.'TYPELIT',
 121        $this->prefix.'TYPECONTACT', $this->prefix.'TYPEURL', $this->prefix.'TYPEPARAMETRE',
 122        $this->prefix.'TYPECARACTERISTIQUE', $this->prefix.'TYPETARIF', $this->prefix.'TYPEDUREETARIF',
 123        $this->prefix.'TYPECHAMBRE', $this->prefix.'TYPECHARGE', $this->prefix.'TYPEDESCRIPTION',
 124        $this->prefix.'DPT', $this->prefix.'INSEE', $this->prefix.'CONSLOISIRS',
 125        $this->prefix.'CARACTERISTIQUE', $this->prefix.'RUBRIQUE', $this->prefix.'RUBRIQUE2',
 126        $this->prefix.'THEME', $this->prefix.'THEME2',
 127        $this->prefix.'INFOTOUR', $this->prefix.'INFOTOUR2', $this->prefix.'PL');
 128  }
 129
 130  /// Tables de nomenclature/communes
 131  public function nomenclatureTablesDpt() {
 132    return array(
 133        'INFOTOUR', $this->prefix.'INSEE',
 134        $this->prefix.'RUBRIQUE', $this->prefix.'RUBRIQUE2', $this->prefix.'THEME',
 135        $this->prefix.'THEME2', $this->prefix.'INFOTOUR', $this->prefix.'INFOTOUR2');
 136  }
 137
 138  /// Tables objet
 139  function objectTables() {
 140    return array(
 141        $this->prefix.'ADR', $this->prefix.'ALBPHOTOINT', $this->prefix.'CHAMBRE',
 142        $this->prefix.'CONTACT', $this->prefix.'DESCRIPTION', $this->prefix.'DETAILSOFREF',
 143        $this->prefix.'LOISIRS', $this->prefix.'PARAMETRE', $this->prefix.'PERIOD',
 144        $this->prefix.'PERIODPROMO', $this->prefix.'PIECE', $this->prefix.'PROMO',
 145        $this->prefix.'SUPPLEMENT', $this->prefix.'TARIF', $this->prefix.'AGREMENT');
 146  }
 147  /// Tables de consolidation
 148  function consolidateTables() {
 149    return array($this->prefix.'CONSCARAC', $this->prefix.'CONSDISTLOISIRS');
 150  }
 151  /// Tables contenant les dispo
 152  function dispoTables() {
 153    return array($this->prefix.'DISPOGEN', $this->prefix.'DISPOREQ');
 154  }
 155  /// Toutes les tables
 156  public function allTables() {
 157    return array_merge($this->nomenclatureTables(), $this->objectTables(), $this->consolidateTables(), $this->dispoTables());
 158  }
 159
 160  /// Supprime une fiche et tout ce qui lui est directement rattachée
 161  /// nodel : liste des tables à ne pas effacer
 162  function del($ar) {
 163    $p = new XParam($ar, array('nodel' => array()));
 164    $nodel = $p->get('nodel');
 165    $oid = $p->get('_selected');
 166    $selectedok = $p->get('_selectedok');
 167    if (($selectedok != 'ok') || empty($oid))
 168      $oid = $p->get('oid');
 169    if (!is_array($oid))
 170      $oid = array($oid);
 171    if (empty($oid))
 172      return;
 173    foreach ($this->objectTables() as $table) {
 174      if (!in_array($table, $nodel) && $table != $this->table) {
 175        if ($table == $this->prefix.'ALBPHOTOINT')
 176          updateQuery('delete from '.$table.' where lie in ("'.implode('", "', $oid).'")');
 177        elseif ($table == $this->prefix.'TARIF')
 178          updateQuery('delete from '.$table.' where lie_ref in ("'.implode('", "', $oid).'") and exercice="'.$this->exercice.'"');
 179        else
 180          updateQuery('delete from '.$table.' where lie_ref in ("'.implode('", "', $oid).'")');
 181      }
 182    }
 183    updateQuery('delete from '.$this->table.' where KOID in ("'.implode('", "', $oid).'")');
 184  }
 185
 186  /// Lance manuellement un import ITEA sur une liste de référence (séparées par des ,)
 187  function manuelImportFromITEA($ar = NULL) {
 188    $p = new XParam($ar, NULL);
 189    $dpt = $p->get('dpt');
 190    $refs = $p->get('refs');
 191    if (empty($dpt)) die('No dpt');
 192    if (empty($refs)) die('No reference');
 193    $o['uid'] = getSessionVar('UID');
 194    $o['function'] = 'importFromITEA';
 195    $o['dpt'] = $dpt;
 196    $o['refs'] = $refs;
 197    $o['forceall'] = 1;
 198    $o['post_import'] = $p->get('post_import');
 199    $date = date('Y-m-d H:i:s');
 200    $scheduler= new XModScheduler();
 201    $roid = $scheduler->createJob($this->_moid, $date, 'Test ITEA', $o, '');
 202    $scheduler->executeJob($roid['oid'], false);
 203    die('finnish');
 204  }
 205
 206  /// Importe les données depuis ITEA via tache scheduler
 207  /// Parametres : clearall => vide toutes les tables objets
 208  ///              forceall => force l'import des fiches deja à jour (donc importe tout)
 209  ///              dpt => liste des departement à importer (séparer par des , )
 210  function importFromITEA(XModScheduler& $sched, $o, $more) {
 211    if (empty($GLOBALS['ITEACONF'][$this->table]))
 212      return 'Error  : no ITEACONF in local.inc';
 213    XDbIni::set('disable_xlinkclean', true);
 214
 215    // Effacement de toutes les tables non nomenclature/consolidation
 216    if (!empty($more->clearall)) {
 217      foreach ($this->objectTables() as $table)
 218        updateQuery('delete from '.$table);
 219    }
 220    // les départements
 221    if ($more->dpt && is_string($more->dpt))
 222      $dpt_select = explode(', ', $more->dpt);
 223    else
 224      $dpt_select = explode(', ', $this->dpts);
 225    echo 'Fonction importFromITEA:'.implode(', ', $dpt_select)."\n";
 226
 227    // Initialisation des variables et recupération des champs spécifiques à la console (commencent par tzr_)
 228    $tzrfields = $del = $error = $new = $maj = $no = $retry = $log_retry = $error2 = array();
 229    foreach ($this->xset->orddesc as $k) {
 230      if (strpos($k, 'tzr_') === 0)
 231        $tzrfields[] = $k;
 232    }
 233    if (!empty($tzrfields))
 234      $sqltzrfields = ', '.implode(', ', $tzrfields);
 235    else
 236      $sqltzrfields = '';
 237
 238    ini_set('soap.wsdl_cache_enabled', 0);
 239
 240    foreach ($dpt_select as $dpt) {
 241      $dptsoap = $dpt.'soap';
 242      $dptsoap_xs = $dpt.'soap_xs';
 243      $soap = new SoapClient($this->$dptsoap, array('exceptions'=>false, 'features'=>SOAP_SINGLE_ELEMENT_ARRAYS));
 244      if ($this->$dptsoap_xs)
 245        $soap_xs = new SoapClient($this->$dptsoap_xs, array('exceptions'=>false, 'features'=>SOAP_SINGLE_ELEMENT_ARRAYS));
 246        
 247      $env = $dpt.'env';
 248      $login = $dpt.'login';
 249      $pass = $dpt.'pass';
 250      $identification = array('env' => $this->$env, 'login' => $this->$login, 'pass' => $this->$pass);
 251      $timebefore = time();
 252      $oids = $oidsmaj = array();
 253      $manual = false;
 254      // les langues pour ce département
 255      $langs = $dpt.'langs';
 256      $langs = $this->$langs;
 257      $langs = explode(',', $langs);
 258      unset($langues);
 259      foreach ($langs as $lang) {
 260        list($tzr_lang, $itea_lang) = explode('=>', trim($lang));
 261        $langues[$tzr_lang] = $itea_lang;
 262        if ($tzr_lang != TZR_DEFAULT_LANG)
 263          $otherlangues[$tzr_lang] = $itea_lang;
 264      }
 265
 266      // Recherche des références à importer
 267      $refs = array();
 268      $to_import = array();
 269      // sur import manuel, les refs sont spécifiées
 270      if(!empty($more->refs)) {
 271        $manual=true;
 272        $mrefs = explode(',',$more->refs);
 273        foreach ($mrefs as $i => $ref) {
 274          // l'exercice en cours uniquement
 275          $exercice = date('Y');
 276          $refs[$ref]->$exercice = true;
 277          $to_import[$exercice][$ref] = (object)array('reference'=>$ref,'type'=>'tzr','date_maj'=>date('d/m/Y'));
 278          $to_import[$exercice+1][$ref] = $to_import[$exercice][$ref];
 279        }
 280      }
 281      // sinon import de toutes les refs mises à jour
 282      else {
 283        // pour l'exercice en cours et le suivant
 284        foreach (array(0, 1) as $i) {
 285          $exercice = date('Y') + $i;
 286          // récupération de la liste
 287          if ($this->$dptsoap_xs)
 288            $lstRef = $this->getXSLstRef($sched, $soap_xs, $o, $identification, $exercice);
 289          else
 290            $lstRef = $this->getLstRef($sched, $soap, $o, $identification, $exercice);
 291          if ($lstRef->produit)
 292            $to_import[$exercice] = array();
 293          elseif ($i == 0) {
 294            // suppression de l'exercice
 295            updateQuery('delete from '.$this->prefix.'TARIF where exercice="'.$exercice.'"');
 296            continue;
 297          } else // exercice +1 vide
 298            break;
 299
 300          // correspondance refs/UPD en base (upditea different selon exercice)
 301          $refs_upd = selectQuery(
 302            'select reference, UPD from '.$this->prefix.'DETAILSOFREF
 303             where lang="'.TZR_DEFAULT_LANG.'" and dpt="'.$this->prefix.'DPT:'.$dpt.'"')
 304            ->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_UNIQUE|PDO::FETCH_COLUMN);
 305
 306          // vérification date maj
 307          foreach ($lstRef->produit as $i => $infos) {
 308            // ce test est-il vraiment nécessaire ?
 309            if (empty($infos->reference) || empty($infos->type))
 310              continue;
 311            $oids[] = $this->getOid($dpt, $infos->reference);
 312            $infos->date_maj = $this->convertDate($infos->date_maj);
 313            if ($infos->date_maj > $refs_upd[$infos->reference] || $more->forceall) {
 314              $to_import[$exercice][$infos->reference] = $infos;
 315            }
 316          }
 317        }
 318      }
 319      $oids = array_values(array_unique($oids));
 320
 321      if (empty($to_import)) {
 322        XLogs::critical("ITEA : importFromITEA error: dpt $dpt, nothing to do");
 323        continue;
 324      }
 325
 326      unset($lstRef, $imported);
 327      // Import des produits
 328      foreach ($to_import as $exercice => $liste_refs) {
 329        foreach ($liste_refs as $ref => $infos) {
 330          XLogs::notice("ITEA Import $ref for $exercice");
 331          $refoid = $this->getOid($dpt, $ref);
 332          unset($infosForRef);
 333          // pour appel recursif à analyseObject
 334          $this->exercice = $exercice;
 335
 336          // si la ref n'est pas déjà importée
 337          if (!isset($imported[$ref])) {
 338            $imported[$ref] = 1; // même si l'import échoue, ne pas importer dans l'exercice suivant (caract !=)
 339            $ors = selectQuery('select KOID, UPD, conspromo' . $sqltzrfields .
 340                              ' from ' . $this->table .
 341                              ' where KOID = "'.$refoid.'" limit 1')->fetch();
 342
 343            echo ' - Post get 1 '.date('H:i:s') . "\n";
 344            foreach ($langues as $tzr_lang => $itea_lang) {
 345              $retry = 0;
 346              do {
 347                sleep($retry);
 348                if ($this->$dptsoap_xs)
 349                  $infosForRef[$tzr_lang] = $soap_xs->getInfosForRef($identification, array('exercice' => $exercice, 'reference' => $ref, 'langue' => $itea_lang));
 350                else
 351                  $infosForRef[$tzr_lang] = $soap->getInfosForRef($identification, array('exercice' => $exercice, 'reference' => $ref, 'langue' => $itea_lang));
 352                $retry++;
 353              } while (empty($infosForRef[$tzr_lang]) && $retry < 5);
 354            }
 355            // Pas de réponse correcte
 356            if(empty($infosForRef[TZR_DEFAULT_LANG]->reference)) {
 357              $error2[$dpt] .= $ref." (".TZR_DEFAULT_LANG.")\n";
 358              continue;
 359            }
 360
 361            $ovalues = array('upditea' => $infos->date_maj);
 362            echo ' - Post get 2 '.date('H:i:s') . "\n";
 363            // suppression de la fiche
 364            if ($ors) {
 365              $maj[$dpt]++;
 366              $delar = $this->delparam[$dpt];
 367              $delar['oid'] = $refoid;
 368              $delar['_nolog'] = true;
 369              $this->del($delar);
 370              // Reprise des champs tzr
 371              foreach ($tzrfields as $field)
 372                $ovalues[$field] = $ors[$field];
 373            } else
 374              $new[$dpt]++;
 375
 376            $this->analyseObject($infosForRef, $this->table, $refoid, $refoid, NULL, $dpt, $ovalues);
 377            echo ' - Post analyse '.date('H:i:s') . "\n";
 378          }
 379          // si la ref est déjà importée (dans un autre exercice)
 380          // on écrase pas les infos de l'exercice en cours par celles du suivant
 381          // Tarifs et promo de l'année uniquement
 382          else {
 383            updateQuery('delete from '.$this->prefix.'TARIF where exercice="'.$exercice.'" and lie_ref="'.$refoid.'"');
 384            foreach ($langues as $tzr_lang => $itea_lang)
 385              $infosForRef[$tzr_lang] = $soap->getInfosForRef($identification, array('exercice' => $exercice, 'reference' => $ref, 'langue' => $itea_lang));
 386            // Tarifs de la reference
 387            foreach ($infosForRef[TZR_DEFAULT_LANG]->tarifs->tarif as $i => $tarif) {
 388              $tarifs[TZR_DEFAULT_LANG] = $tarif;
 389              foreach ($otherlangues as $tzr_lang => $itea_lang)
 390                $tarifs[$tzr_lang] = $infosForRef[$tzr_lang]->tarifs->tarif[$i];
 391              $this->analyseObject($tarifs, $this->prefix.'TARIF', $refoid, NULL, $refoid, $dpt);
 392            }
 393            // Promos de la reference
 394            foreach ($infosForRef[TZR_DEFAULT_LANG]->promos->promo as $i => $promo){
 395              $promos[TZR_DEFAULT_LANG] = $promo;
 396              foreach ($otherlangues as $tzr_lang => $itea_lang)
 397                $promos[$tzr_lang] = $infosForRef[$tzr_lang]->promos->promo[$i];
 398              $this->analyseObject($promos, $this->prefix.'PROMO', $refoid, NULL, $refoid, $dpt);
 399            }
 400            // Tarifs des suppléments de la référence
 401            // correspondance libelle -> oid
 402            $suppl_libelle_oid = selectQuery(
 403                'select libelle, koid from '.$this->prefix.'SUPPLEMENT
 404                 where lie="'.$refoid.'" and lang="'.TZR_DEFAULT_LANG.'"')
 405                ->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_UNIQUE|PDO::FETCH_COLUMN);
 406            foreach ($infosForRef[TZR_DEFAULT_LANG]->supplements->supplement as $i => $suppl) {
 407              $oid_suppl = $suppl_libelle_oid[$suppl->libelle];
 408              foreach ($suppl->prix->tarif as $j => $tarif) {
 409                $suppls[TZR_DEFAULT_LANG] = $suppl;
 410                $tarifs[TZR_DEFAULT_LANG] = $tarif;
 411                foreach ($otherlangues as $tzr_lang => $itea_lang) {
 412                  $tarifs[$tzr_lang] = $infosForRef[$tzr_lang]->supplements->supplement[$i]->prix->tarif[$j];
 413                }
 414                $this->analyseObject($tarifs, $this->prefix.'TARIF', $refoid, NULL, $oid_suppl, $dpt);
 415              }
 416            }
 417            // Tarifs des chambres et des suppléments des chambres
 418            // correspondance num -> oid
 419            $chambre_num_oid = selectQuery(
 420                'select numeroChambre, KOID from '.$this->prefix.'CHAMBRE
 421                 where lie="'.$refoid.'" and lang="'.TZR_DEFAULT_LANG.'"')
 422                ->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_UNIQUE|PDO::FETCH_COLUMN);
 423            foreach ($infosForRef[TZR_DEFAULT_LANG]->chambres->chambre as $i => $chambre) {
 424              $oid_chambre = $chambre_num_oid[$chambre->numeroChambre];
 425              foreach ($chambre->tarifs->tarif as $j => $tarif) {
 426                $tarifs[TZR_DEFAULT_LANG] = $tarif;
 427                foreach ($otherlangues as $tzr_lang => $itea_lang) {
 428                  $tarifs[$tzr_lang] = $infosForRef[$tzr_lang]->chambres->chambre[$i]->tarifs->tarif[$j];
 429                }
 430                $this->analyseObject($tarifs, $this->prefix.'TARIF', $refoid, NULL, $oid_chambre, $dpt);
 431              }
 432                // les suppléments de la chambre
 433                foreach ($chambre->supplements->supplement as $j => $suppl){
 434                  // correspondance libelle -> oid
 435                  $suppl_libelle_oid = selectQuery(
 436                      'select libelle, KOID from '.$this->prefix.'SUPPLEMENT
 437                       where lie="'.$oid_chambre.'" and lang="'.TZR_DEFAULT_LANG.'"')
 438                      ->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_UNIQUE|PDO::FETCH_COLUMN);
 439                  if ($oid_suppl = $suppl_libelle_oid[$suppl->libelle]) {
 440                    foreach ($suppl->prix->tarif as $k => $tarif) {
 441                      $tarifs[TZR_DEFAULT_LANG] = $tarif;
 442                      foreach ($otherlangues as $tzr_lang => $itea_lang)
 443                      $tarifs[$tzr_lang] = $infosForRef[$tzr_lang]->chambres->chambre[$i]->supplements->supplement[$j]->prix->tarif[$k];
 444                      $this->analyseObject($tarifs, $this->prefix.'TARIF', $refoid, NULL, $oid_suppl, $dpt);
 445                    }
 446                  }
 447                }
 448              }
 449          } // import Y+1
 450          // Consolidation
 451          $this->consolidateRef($refoid);
 452          $oidsmaj[] = $refoid;
 453          XLogs::notice("ITEA Import $ref for $exercice ok");
 454        } // foreach liste_refs
 455      } // foreach to_import
 456
 457      // Supression des produit non vus dans cet import pour le departement en cours
 458      if (!$manual && !empty($oids)) {
 459        $oids_todel = selectQuery('select distinct KOID from '.$this->table.
 460                          ' where KOID NOT IN("'.implode('", "', $oids).'") and '.
 461                          ' dpt = "'.$this->prefix.'DPT:'.$dpt.'"')
 462                          ->fetchAll(PDO::FETCH_COLUMN);
 463        XLogs::critical('ITEA import '.count($oids_todel).' à effacer');
 464        foreach ($oids_todel as $oid) {
 465          $this->del(array('oid' => $oid, '_nolog' => true));
 466          $del[$dpt]++;
 467        }
 468      }
 469
 470      // Création des rubriques, info tour et themes globaux + consolidation finale
 471      if (!empty($oidsmaj)) {
 472        $this->duplicateRubToRubGlob(array('table' => $this->prefix.'RUBRIQUE', 'dpt' => $dpt));
 473        $this->duplicateRubToRubGlob(array('table' => $this->prefix.'INFOTOUR', 'dpt' => $dpt));
 474        $this->duplicateRubToRubGlob(array('table' => $this->prefix.'THEME', 'dpt' => $dpt));
 475        $this->consolidateRefs($oidsmaj, $dpt);
 476      }
 477
 478      // Rapport dur le departement
 479      $timing = time()-$timebefore;
 480      $ret .= 'Département : '.$dpt."\n";
 481      $ret .= 'Heure début : '.date("c", $timebefore)."\n";
 482      $ret .= 'Heure fin : '.date("c", time())."\n";
 483      $ret .= 'Timing : '.$timing." sec.\n";
 484      $ret .= 'Total : '.count($refs)."\n";
 485      $ret .= 'A jour : '.$no[$dpt]."\n";
 486      $ret .= 'Nouveaux : '.$new[$dpt]."\n";
 487      $ret .= 'Mis à jour : '.$maj[$dpt]."\n";
 488      $ret .= 'Erreur : '.$error[$dpt]."\n";
 489      $ret .= 'Erreur getInfosForRef vide : '.$error2[$dpt]."\n";
 490      $ret .= 'Nb itérations sur err : '.$log_retry[$dpt]."\n";
 491      $ret .= 'Total traités : '.($no[$dpt]+$maj[$dpt]+$new[$dpt]+$error[$dpt])."\n";
 492      $ret .= 'Supprimé : '.$del[$dpt]."\n";
 493      echo str_replace("\n", '<br>', $ret);
 494    }
 495    $sched->setStatusJob($o->KOID, 'running', $ret);
 496    // execution traitements supplémentaires
 497    if (method_exists($this, 'postImport') && (!$manual || $o->post_import == 1)) {
 498      $sched->setStatusJob($o->KOID, 'running', 'calling postImport');
 499      $this->postImport($sched, $o, $more, $oidsmaj);
 500    }
 501    $sched->setStatusJob($o->KOID, 'finished', 'done');
 502    XDbIni::clear('disable_xlinkclean');
 503    return $ret;
 504  }
 505
 506  /// Recupere la liste des references pour un exercice
 507  /// utilise la version améliorée xs_getLstRef
 508  function getXSLstRef(&$sched, &$soap_xs, $o, $identification, $exercice) {
 509    $retry=0;
 510    do {
 511      $sched->setStatusJob($o->KOID, 'running', "Fonction getXSLstRef $exercice : Try $retry\n");
 512      $lstref->exercice = $exercice;
 513      $rep = $soap_xs->xs_getLstRef($identification, $lstref);
 514      $retry++;
 515    } while (empty($rep->produit) && $retry < 2);
 516    if (empty($rep->produit) || $retry == 2){
 517      $sched->setStatusJob($o->KOID, 'running','Fonction getXSLstRef : Echec - '.$retry." retries\n");
 518      return false;
 519    }
 520    return $rep;
 521  }
 522
 523  /// Recupere la liste des references pour un exercice
 524  /// utilise la version itea getLstRef
 525  function getLstRef(&$sched, &$soap, $o, $identification, $exercice) {
 526    $retry=0;
 527    do {
 528      $sched->setStatusJob($o->KOID, 'running', "Fonction getLstRef $exercice : Try $retry\n");
 529      $lstref->exercice = $exercice;
 530      $rep = $soap->getLstRef($identification, $lstref);
 531      $retry++;
 532    } while (empty($rep->produit) && $retry < 2);
 533    if (empty($rep->produit) || $retry == 2){
 534      $sched->setStatusJob($o->KOID, 'running','Fonction getLstRef : Echec - '.$retry." retries\n");
 535      return false;
 536    }
 537    return $rep;
 538  }
 539
 540  /// Analyse un objet XML
 541  /// rep => tableau avec obj xml par langue
 542  /// table => table de destination de l'objet
 543  /// refoid => oid du produit de reference
 544  /// oid => oid de la fiche a creer
 545  /// parent => oid du parent
 546  /// dpt => departement
 547  /// values => valeurs à passer au procInput/procEdit
 548  function analyseObject(&$rep, $table, $refoid, $oid = NULL, $parent = NULL, $dpt = NULL, $values = array()) {
 549    global $TZR_DB;
 550    $repbase = &$rep[TZR_DEFAULT_LANG];
 551    $forceedit = false;
 552    if (!XSystem::tableExists($table)) return;
 553    $oxset = XDataSource::objectFactoryHelper8('BCLASS=XDSTable&SPECS='.$table);
 554
 555    // Génération de l'oid si pas passé en parametre
 556    if (empty($oid)) {
 557      if ($table == $this->prefix.'CARACTERISTIQUE')
 558        $oid = substr($table.':'.str_replace('?', '-', $repbase->valeur).'-'.$repbase->id . '-' .$dpt.'_'. md5($repbase->libelleLong), 0, 40);
 559      elseif ($table == $this->prefix.'TYPELANGUE')
 560        $oid = $table.':'.rewriteToAscii($repbase->code);
 561//         // les promos sont identiques pour tout les hébergements mais elles sont en sf
 562//       elseif ($table == $this->prefix.'PROMO')
 563//         $oid = $table.':'.$dpt.'_'.$repbase->id;
 564      elseif (in_array($table, $this->descrType['tables'])) {
 565        $code = $this->convertText($repbase->code);
 566        // Inversion code/description de INFOTOUR pour NOM_INFO_TOURISTIQUE
 567        if ($code == 'NOM_INFO_TOURISTIQUE') {
 568          foreach ($rep as $lang => &$replang) {
 569            $replang->code = $replang->description;
 570            $replang->description = '';
 571          }
 572          unset($replang);
 573          $code = $this->convertText($repbase->code);
 574        }
 575        $descr = $this->convertText($repbase->description);
 576        $oid = selectQuery('select KOID from '.$table.' where code = "'.addslashes($code).'" '.
 577                           'and description = "'.addslashes($descr).'" '.
 578                           'and dpt = "'.$this->prefix.'DPT:'.$dpt.'" and LANG = "'.TZR_DEFAULT_LANG.'" limit 1')
 579                           ->fetch(PDO::FETCH_COLUMN);
 580      }
 581    }
 582    if (empty($oid)) {
 583      $oid = $oxset->getNewOID();
 584    }
 585    $objexist = selectQuery('select count(KOID) from '.$table.'  where KOID = "'.$oid.'" and LANG = "'.TZR_DEFAULT_LANG.'"')
 586                ->fetch(PDO::FETCH_COLUMN);
 587    if (($table == $this->prefix.'TYPELANGUE' || $table == $this->prefix.'CARACTERISTIQUE') && $objexist)
 588      return $oid;
 589    if (!empty($parent))
 590      $values['lie'] = $parent;
 591    $values['newoid'] = $oid;
 592    $values['lie_ref'] = $refoid;
 593    $values['_nolog'] = true;
 594    $values['LANG_DATA'] = TZR_DEFAULT_LANG;
 595    $values['exercice'] = $this->exercice;
 596
 597    foreach ($repbase as $field => &$value) {
 598      // Valeur classique (string, int, nomenclature...)
 599      if (!is_object($value) && !($field == 'caracteristiques' && is_array($value))) {
 600	$ftype = $oxset->desc[$field]->ftype;
 601	switch($ftype) {
 602	case 'XDateDef':
 603	  $values[$field] = $this->convertDate($value);
 604	  break;
 605	case 'XUrlDef':
 606          $this->prepareImage('img', $value, $values);
 607	  $values[$field]['url'] = $value;
 608	  break;
 609	case 'XStringSetDef':
 610	  $soid = selectQuery('select SOID from SETS where STXT = "'.$value.'" and SLANG = "'.TZR_DEFAULT_LANG.'" and FIELD = "'.$field.'" '.
 611			     'and STAB = "'.$table.'" limit 1')->fetch(PDO::FETCH_COLUMN);
 612	  if (empty($soid)) {
 613	    $soid = selectQuery('select max(SOID)+1 as SOID from SETS')->fetch(PDO::FETCH_COLUMN);
 614	    $order = selectQuery('select max(SORDER)+1 as max from SETS where STAB = "'.$table.'" and FIELD = "'.$field.'"')->fetch(PDO::FETCH_COLUMN);
 615	    if (!empty($order))
 616              $order = 1;
 617	    foreach ($rep as $lang => $replang) {
 618	      updateQuery('insert into SETS (SOID, FIELD, STAB, SLANG, STXT, SORDER) values ("'.$soid.'", "'.$field.'", "'.$table.'", '.
 619			  '"'.$lang.'", "'.$value.'", "'.$order.'")');
 620	    }
 621	  }
 622	  $values[$field] = $soid;
 623	  break;
 624	case 'XLinkDef':
 625	  $target = $oxset->desc[$field]->target;
 626	  if (!is_array($value))
 627            $value = array($value);
 628	  foreach ($value as $v) {
 629	    if (!empty($v)) {
 630	    // suppression traitement des pictos loisirs
 631	    // on doir récupérer les libellés dans toutes les langues
 632	    // le champ picto devient le lien sur ITEA_PL
 633	    // !!! changement fonctionnalité v7
 634              if ($field == 'languesParlees') {
 635                $rs = selectQuery('select KOID from '.$target.' where code = "'.$v->code.'" limit 1');
 636                if ($rs->rowCount() == 0) {
 637                  $xset = XDataSource::objectFactoryHelper8('BCLASS=XDSTable&SPECS='.$target);
 638                  $loid = $target.':'.$v->code;
 639                  $xset->procInput(array('newoid' => $loid, 'code' => $v->code, 'libelle' => $v->libelle, '_nolog' => true));
 640                  $values[$field][] = $loid;
 641                } else {
 642                  $values[$field][] = $rs->fetch(PDO::FETCH_COLUMN);
 643                }
 644              } else {
 645                $rs = selectQuery('select KOID from '.$target.' where code = "'.$v.'" limit 1');
 646                if ($rs->rowCount() == 0) {
 647                  $xset = XDataSource::objectFactoryHelper8('BCLASS=XDSTable&SPECS='.$target);
 648                  $loid = $target.':'.rewriteToAscii(str_replace('?', '-', $v));
 649                  $xset->procInput(array('newoid' => $loid, 'code' => $v, 'libelle' => $v, '_nolog' => true));
 650                  $values[$field][] = $loid;
 651                } else {
 652                  $values[$field][] = $rs->fetch(PDO::FETCH_COLUMN);
 653                }
 654              }
 655	    }
 656	  }
 657	  break;
 658	default:
 659	  if ($field == 'id') $field = 'refid';
 660	  if ($field == 'classementLabel' and $value == '9') $value = '0';
 661          // traitement des pictos loisirs
 662          if ($table == $this->prefix.'LOISIRS' && $field == 'libelleLong') {
 663            $picto = $this->getDistinctLoisir($value);
 664            $picto_table = $this->prefix.'PL';
 665            $loid = $picto_table.':'.md5($value);
 666            $rs = selectQuery('select KOID from '.$picto_table.' where KOID = "'.$loid.'" limit 1');
 667            if ($rs->rowCount() == 0) {
 668              $xset = XDataSource::objectFactoryHelper8('BCLASS=XDSTable&SPECS='.$picto_table);
 669              $xset->procInput(array('newoid' => $loid, 'code' => $value, '_nolog' => true));
 670              $values['picto'][] = $loid;
 671            } else {
 672              $values['picto'][] = $rs->fetch(PDO::FETCH_COLUMN);
 673            }
 674          }
 675          $values[$field] = $this->convertText($value);
 676	  if ($oxset->desc[$field]->translatable) {
 677	    foreach ($rep as $lang => $replang) {
 678              $tradvalues[$lang][$field] = $this->convertText($replang->$field);
 679	    }
 680	  }
 681	  break;
 682	}
 683      } else {
 684	// On veut recuperer un sous objet pour le mettre directement dans la fiche en cours
 685	if (in_array($field, $this->directsubdata[$table])) {
 686	  $obj = array();
 687	  foreach ($rep as $lang => $replang) {
 688            $obj[$lang] = $replang->$field;
 689          }
 690	  $foid = $this->analyseObject($obj, $table, $refoid, $oid, NULL, $dpt);
 691	  $forceedit = true;
 692        } elseif ($subfield = $this->directuniquesubdata[$table][$field]) {
 693          $values[$field] = $this->convertText($value->$subfield);
 694          if ($oxset->desc[$field]->translatable) {
 695            foreach ($rep as $lang => $replang) {
 696              $replang->$field->$subfield = $this->convertText($replang->$field->$subfield);
 697              $tradvalues[$lang][$field] = addslashes($replang->$field->$subfield);
 698            }
 699          }
 700	// Lien vers un objet complexe unique (donc en lien dans la table) (id loisir)
 701	} elseif (isset($oxset->desc[$field]) && !$oxset->desc[$field]->multivalued) {
 702	  $obj = array();
 703	  foreach ($rep as $lang => $replang)
 704            $obj[$lang] = $replang->$field;
 705	  $foid = $this->analyseObject($obj, $oxset->desc[$field]->target, $refoid, NULL, NULL, $dpt);
 706	  $values[$field] = $foid;
 707	// Lien vers un objet complexe multiple en lien multiple ou en sous fiches
 708	} else {
 709	  // Cas particulier des caractéristiques toutes foireuses dans pieces et chambres
 710	  if ($field == 'caracteristiques' && is_array($value)) {
 711	    foreach ($rep as $lang => &$replang) {
 712	      foreach ($replang->$field as &$tmp)
 713                $tmp = (object)$tmp;
 714	      $replang->$field = (object)array('carateristique' => $replang->$field);
 715	    }
 716	    $value = $rep[TZR_DEFAULT_LANG]->$field;
 717	  }
 718
 719	  foreach ($value as $t => $objs) {
 720	    foreach ($rep as $lang => &$replang) {
 721	      if (!is_array($replang->$field->$t))
 722                $replang->$field->$t = array($replang->$field->$t);
 723	    }
 724	    unset($replang);
 725	    foreach ($rep[TZR_DEFAULT_LANG]->$field->$t as $i => $object_deflang) {
 726	      $obj = array();
 727              // les descriptifsComp ne sont pas les mêmes dans les différentes langues
 728              // recherche de correspondance sur type et code
 729              if ($field == 'descriptifsComp') {
 730                $obj[TZR_DEFAULT_LANG] = $object_deflang;
 731                foreach ($rep as $lang => $replang) {
 732                  if ($lang == TZR_DEFAULT_LANG)
 733                    continue;
 734                  foreach ($replang->$field->$t as $j => $object_other_lang) {
 735                    if ($object_other_lang->type == $object_deflang->type
 736                     && $object_other_lang->code == $object_deflang->code) {
 737                      $obj[$lang] = $object_other_lang;
 738                    }
 739                  }
 740                }
 741              }
 742              // sinon, on prend dans les objects dans l'ordre de l'index
 743              else
 744                foreach ($rep as $lang => $replang) {
 745                  $objlist = $replang->$field->$t;
 746                  $obj[$lang] = $objlist[$i];
 747                }
 748	      $isok = false;
 749	      if ($field == 'descriptifsComp' && $table == $this->prefix.'DETAILSOFREF') {
 750		if (in_array($obj[TZR_DEFAULT_LANG]->type, $this->descrType['link'])) {
 751		  $lower = strtolower($obj[TZR_DEFAULT_LANG]->type);
 752		  $newf = $this->descrType['fields'][$lower];
 753		  if (!in_array($lower, $this->descrType['notlink'])) {
 754                    $values[$newf][] = $this->analyseObject($obj, $oxset->desc[$newf]->target, $refoid, NULL, NULL, $dpt, $this->descrType['cplt'][$lower]);
 755                  }
 756		  $isok = true;
 757		} elseif (in_array($obj[TZR_DEFAULT_LANG]->type, $this->descrType['no'])) {
 758		  continue;
 759		}
 760	      } elseif ($field == 'urls' && $table == $this->prefix.'DETAILSOFREF') {
 761		// Gestion de la photo principale + vignette
 762		if (isset($oxset->desc[strtolower($obj[TZR_DEFAULT_LANG]->type)])) {
 763		  $isok = true;
 764		  $newf = strtolower($obj[TZR_DEFAULT_LANG]->type);
 765		  if ($oxset->desc[$newf]->ftype == 'XImageDef') {
 766                    $this->prepareImage($newf, $obj[TZR_DEFAULT_LANG]->url, $values);
 767                    $values[$newf] = $obj[TZR_DEFAULT_LANG]->url;
 768                  } else
 769                    $values[$newf]['url'] = $obj[TZR_DEFAULT_LANG]->url;
 770		// Gestion de l'album photo
 771		} elseif (substr(strtolower($obj[TZR_DEFAULT_LANG]->type), 0, 5) == 'photo' && strtolower($obj[TZR_DEFAULT_LANG]->type) != 'photo') {
 772		  $isok = true;
 773		  $this->analyseObject($obj, $this->prefix.'ALBPHOTOINT', $refoid, NULL, $oid, $dpt);
 774		}
 775	      } elseif ($field == 'telephones' && $table == $this->prefix.'CONTACT') {
 776		$isok = true;
 777		if (isset($oxset->desc[strtolower($obj[TZR_DEFAULT_LANG]->type)])) {
 778		  $newf = strtolower($obj[TZR_DEFAULT_LANG]->type);
 779		  if (empty($values[$newf]))
 780                    $values[$newf] = $obj[TZR_DEFAULT_LANG]->numero;
 781		  else
 782                    $values[$newf] .= ', '.$obj[TZR_DEFAULT_LANG]->numero;
 783		}
 784	      } elseif ($table == $this->prefix.'PERIODPROMO') {
 785		$isok = true;
 786		// Consolidation des champs période directement dans la table ITEA_PERIODPROMO
 787		if (!isset($oxset->desc[$field])) {
 788		  $values[$t.$field] = $this->convertDate($obj[TZR_DEFAULT_LANG]);
 789		}
 790	      }
 791
 792	      if (!$isok) {
 793		if (isset($oxset->desc[$field]) && $oxset->desc[$field]->multivalued) {
 794		  $values[$field][] = $this->analyseObject($obj, $oxset->desc[$field]->target, $refoid, NULL, NULL, $dpt);
 795		} else {
 796		  $values[$field][] = $this->analyseObject($obj, strtoupper($this->prefix.''.$t), $refoid, NULL, $oid, $dpt);
 797		}
 798	      }
 799	    }
 800	  }
 801	}
 802      }
 803    }
 804
 805    if ($table == $this->prefix.'DETAILSOFREF') {
 806      // Coordonnées TZR
 807      if (!empty($values['latitude']) && !empty($values['longitude'])) {
 808	$values['coordx'] = $values['latitude'].';'.$values['longitude'].';M;N/A;'.date('Y-m-d H:i:s');
 809      }
 810      // Caractéristiques consolidées
 811      if ($this->needconscaract && is_object($repbase->caracteristiques)) {
 812	foreach ($repbase->caracteristiques->caracteristique as $c) {
 813	  if ($c->valeur == 'O') {
 814	    $value = $this->getConsCarac($c->id, $values['type'], $dpt);
 815	    if (!empty($value)) $values['conscarac'][] = $value;
 816	  }
 817	}
 818      }
 819    }
 820    if ($dpt) $values['dpt'] = $this->prefix.'DPT:'.$dpt;
 821
 822    // Insere ou edite l'entrée
 823    if (empty($objexist) && !$forceedit) {
 824      // Boucle pour forcer les champs numériques à NULL s'ils ne sont pas renseignés (car sinon 0, et c'est pas bien)
 825      foreach ($oxset->desc as $fn => &$fo) {
 826	if ($fo->ftype == 'XRealDef' && !isset($values[$fn])) $values[$fn] = '';
 827      }
 828      $values['_nolog'] = true;
 829      $ret = $oxset->procInput($values);
 830    } else {
 831      $ret['oid'] = $values['oid'] = $oid;
 832      $values['_nolog'] = true;
 833      $oxset->procEdit($values);
 834    }
 835
 836    // Traduction
 837    if ($oxset->getTranslatable()) {
 838      foreach ($tradvalues as $lang => $values) {
 839	if ($lang != TZR_DEFAULT_LANG) {
 840	  $q = array();
 841	  foreach ($values as $f => $v) {
 842	    if (!empty($v)) $q[] = $f.' = '.$TZR_DB->quote($v);
 843	  }
 844	  if (!empty($q))
 845            updateQuery('update '.$table.' set '.implode(', ', $q).' where KOID = "'.$ret['oid'].'" and LANG = "'.$lang.'"');
 846	}
 847      }
 848    }
 849    return $ret['oid'];
 850  }
 851
 852  /// Import les disponibilité depuis ITEA via tache scheduler
 853  function importDispoFromITEA(XModScheduler& $sched, $o, $more) {
 854    if (empty($GLOBALS['ITEACONF'][$this->table]))
 855      return 'Error  : no ITEACONF in local.inc';
 856
 857    // Si des imports de ressources sont en cours, on reporte l'import des dispo d'une heure pour ne pas trop ralentir la recuperation
 858    $nb = countSelectQuery('select count(KOID) from TASKS where title like "Import ITEA%" and status = "running"');
 859    if ($nb > 0) {
 860      updateQuery('UPDATE TASKS SET status = "scheduled", rem = "'.date('Y-m-d H:i:s').' : Reporté car import ITEA en cours", '.
 861                  'ptime = "'.date('Y-m-d H:i:s', strtotime('+1 hour')).'" WHERE KOID = "'.$o->KOID.'"', false);
 862      return;
 863    }
 864
 865    // Paramètre des recup : clé => numero du jour dans la semaine
 866    //                       valeur => tableau : cle => duree
 867    //                                         valeur => tableau des types
 868    // donner une chance à la class d'implémentation de personnaliser la conf
 869    if (method_exists($this, 'getDispoConf'))
 870      $torecup = $this->getDispoConf();
 871    else {
 872      if ($more->dtype == 'other') {
 873        $types = selectQuery('select distinct KOID from '.$this->prefix.'TYPEPRODUIT '.
 874                    'where KOID not in("'.$this->prefix.'TYPEPRODUIT:g", "'.$this->prefix.'TYPEPRODUIT:h)"')
 875                    ->fetchAll(PDO::FETCH_COLUMN);
 876        $torecup = array('5' => array('2' => $types, '7' => $types, '14' => $types, '21' => $types));
 877      } else {
 878        $torecup = array(
 879            '5' => array('2' => array($this->prefix.'TYPEPRODUIT:g', $this->prefix.'TYPEPRODUIT:h'),
 880                        '7' => array($this->prefix.'TYPEPRODUIT:g', $this->prefix.'TYPEPRODUIT:h'),
 881                        '8' => array($this->prefix.'TYPEPRODUIT:h'),
 882                        '14' => array($this->prefix.'TYPEPRODUIT:g', $this->prefix.'TYPEPRODUIT:h'),
 883                        '15' => array($this->prefix.'TYPEPRODUIT:h'),
 884                        '21' => array($this->prefix.'TYPEPRODUIT:g', $this->prefix.'TYPEPRODUIT:h')
 885                        ),
 886            '6' => array('7' => array($this->prefix.'TYPEPRODUIT:g', $this->prefix.'TYPEPRODUIT:h'),
 887                        '8' => array($this->prefix.'TYPEPRODUIT:h'),
 888                        '14' => array($this->prefix.'TYPEPRODUIT:g', $this->prefix.'TYPEPRODUIT:h'),
 889                        '15' => array($this->prefix.'TYPEPRODUIT:h'),
 890                        '21' => array($this->prefix.'TYPEPRODUIT:g', $this->prefix.'TYPEPRODUIT:h')
 891                        )
 892                      );
 893      }
 894    }
 895    $ts = time();
 896    $end = date('Y-m-d',strtotime('+12 month'));
 897    $liste = array();
 898    if (!empty($more->dpts))
 899      $dpts = $more->dpts;
 900    else
 901      $dpts = $this->dpts;
 902    if (empty($dpts))
 903      return 'Erreur : aucun département spécifié';
 904    $dpts = explode(',', $dpts);
 905    foreach ($dpts as $dpt){
 906      $liste[trim($dpt)] = array();
 907    }
 908    $ds_dispogen = XDataSource::objectFactoryHelper8('BCLASS=XDSTable&SPECS='.$this->prefix.'DISPOGEN');
 909    updateQuery('delete from '.$this->prefix.'DISPOGEN where deb < curDate()');
 910    do {
 911      $isodate = date('Y-m-d', $ts);
 912      $date = date('d/m/Y', $ts);
 913      $dayinweek = date('N', $ts);
 914      foreach ($torecup[$dayinweek] as $duree => $types) {
 915        foreach ($types as $type) {
 916          echo date('H:i:s').' => ';
 917          $refs = $this->xset->getDispoFromITEA($liste, $date, $duree, $type);
 918          echo $date.' - '.$duree.' - '.$type.' - '.(strpos($refs, 'soaperrorcode:') !== false? $refs: count(explode(';', $refs)))."\n";
 919          updateQuery('delete from '.$this->prefix.'DISPOGEN where deb = "'.$isodate.'" and duree = "'.$duree.'" and type = "'.$type.'"');
 920          if (strpos($refs, 'soaperrorcode:') === false) {
 921            $ds_dispogen->procInput(array('type' => $type, 'duree' => $duree, 'deb' => $isodate, 'refs' => $refs, '_nolog' => true));
 922          }
 923        }
 924        if (is_object($sched)) {
 925          $ns = $sched->setStatusJob($o->KOID, 'running', $isodate.'-'.$duree);
 926          if ($ns===false) return; // ns = false si la tache n'existe plus
 927        }
 928      }
 929
 930      $ts = strtotime($isodate.' +1 day');
 931    } while ($isodate<=$end);
 932    // suppression des dispos dépassées
 933    updateQuery('delete from '.$this->prefix.'DISPOGEN where date_add(deb, interval duree day) < now()');
 934    // execution traitements supplémentaires
 935    if (method_exists($this, 'postImportDispo')) {
 936      $sched->setStatusJob($o->KOID, 'running', 'calling postImportDispo');
 937      $this->postImportDispo($sched, $o, $more);
 938    }
 939    $sched->setStatusJob($o->KOID, 'finished', 'done');
 940  }
 941
 942  /// Prepare un fichier image à partir d'une url
 943  function prepareImage($field, $url, &$values) {
 944    $file = TZR_TMP_DIR.'ITEA'.uniqid();
 945    $retry = 0;
 946    do {
 947      $content = file_get_contents($url);
 948      $retry++;
 949    } while(!$content && $retry < 3);
 950
 951    if (empty($content)) {
 952      XLogs::notice('xmoditea::prepareImage cannot fetch '.$url);
 953    } else {
 954      file_put_contents($file, $content);
 955      $mimeClasse = XMimeTypes::getInstance();
 956      $mime = $mimeClasse->get_file_type($file);
 957      if ($mimeClasse->isImage($mime)) {
 958	$values[$field.'_title'] = '';
 959	$values[$field.'_HID'] = array('old' => 'N%3B');
 960	$values[$field] = 1;
 961	$_FILES[$field]['tmp_name'] = $file;
 962	$_FILES[$field]['type'] = $mime;
 963	$_FILES[$field]['name'] = $url;
 964	$_FILES[$field]['size'] = filesize($file);
 965      }
 966    }
 967  }
 968
 969  /// Convertion de texte ITEA en texte normal
 970  function convertText($text) {
 971    $from = array("\xc2\x92", "\xc2\x9C", "\xc2\x80");
 972    $to = array("'", "oe", "€");
 973    $text = str_replace($from, $to, $text);
 974    convert_charset($text, 'UTF-8', 'ISO-8859-15');
 975    cp1252_replace($text);
 976    convert_charset($text, 'ISO-8859-15', 'UTF-8');
 977    return $text;
 978  }
 979
 980  /// Convertit une date ITEA au format international
 981  function convertDate($date) {
 982    if (!preg_match('/^([0-9]{2})\/?([0-9]{2})\/?([0-9]{4}|[0-9]{2})$/', $date, $matches))
 983      return $date;
 984    if (strlen($matches[3]) == 2)
 985      if ($matches[3] >= 50)
 986        $matches[3] = '19'.$matches[3];
 987      else
 988        $matches[3] = '20'.$matches[3];
 989    return $matches[3] . '-' . $matches[2] . '-' . $matches[1];
 990  }
 991
 992  /// Recupere une caracteristique consolidée à partir de son id, de son type et de son departement
 993  function getConsCarac($id, $type, $dpt) {
 994    if (is_array($type))
 995      $type = $type[0];
 996    $type = str_replace($this->prefix.'TYPEPRODUIT:', '', $type);
 997    if (empty($this->_cache->conscarac)) {
 998      $rs = &selectQuery('select * from '.$this->prefix.'CONSCARAC');
 999      while($ors = $rs->fetch()) {
1000	foreach ($ors as $f => $v) {
1001	  if (strpos($f, 'c')!==0 || empty($v)) continue;
1002	  $lid = explode(', ', $v);
1003	  foreach ($lid as $fooid) {
1004	    $this->_cache->conscarac[$f][$fooid] = $ors['KOID'];
1005	  }
1006	}
1007      }
1008    }
1009    return $this->_cache->conscarac['c'.$type.$dpt][$id];
1010  }
1011
1012  /// Recupere un libelle Loisir unique
1013  function getDistinctLoisir($lib) {
1014    if (empty($this->_cache->consloisirs)) {
1015      $this->_cache->consloisirs = selectQuery('select src, dest from '.$this->prefix.'CONSLOISIRS')
1016                                  ->fetchAll(PDO::FETCH_COLUMN|PDO::FETCH_UNIQUE);
1017    }
1018    if (!empty($this->_cache->consloisirs[$lib]))
1019      return $this->_cache->consloisirs[$lib];
1020    else
1021      return $lib;
1022  }
1023
1024  /// Execute toutes les consolidations d'un departement (utilisé pour une consolidation globale manuelle)
1025  function executeAllConsolidation($ar = NULL) {
1026    ini_set('max_execution_time', 3600);
1027    $p = new XParam($ar, array('dpt' => '04'));
1028    $dpt = $p->get('dpt');
1029    if (empty($dpt)) return 'no dpt';
1030    $oids = selectQuery('select KOID from '.$this->table.
1031                        ' where dpt = "'.$this->prefix.'DPT:'.$dpt.'" and LANG = "'.TZR_DEFAULT_LANG.'"')
1032                        ->fetchAll(PDO::FETCH_COLUMN);
1033    foreach ($oids as $oid)
1034      $this->consolidateRef($oid);
1035    $this->duplicateRubToRubGlob(array('table' => $this->prefix.'RUBRIQUE', 'dpt' => $dpt));
1036    $this->duplicateRubToRubGlob(array('table' => $this->prefix.'INFOTOUR', 'dpt' => $dpt));
1037    $this->duplicateRubToRubGlob(array('table' => $this->prefix.'THEME', 'dpt' => $dpt));
1038    $this->consolidateRefs($oids, $dpt);
1039
1040    echo 'ok';
1041  }
1042
1043  /// Consolide une fiche (appelé pour chaque fiche)
1044  /// (pour une consolidation complete, consolidateRefs doit etre aussi appelée)
1045  /// Retourne l'ors de la fiche pour un enrichissement eventuel de la fonction
1046  function consolidateRef($oid, $edit = true) {
1047    if (empty($oid)) return;
1048    echo ' - Debut consolidation '.date('H:i:s') . "\n";
1049
1050    $orsref = selectQuery('select * from '.$this->table.
1051                          ' where KOID = "'.$oid.'" and LANG = "'.TZR_DEFAULT_LANG.'" limit 1')
1052                          ->fetch();
1053    if (!$orsref)
1054      return;
1055    $ar = array();
1056    // Tarif min max
1057    if (!empty($this->xset->desc['constarifmin']) && !empty($this->xset->desc['constarifmax'])) {
1058      if ($orsref['type'] == $this->prefix.'TYPEPRODUIT:h')
1059        $ors = selectQuery('select min(montant) as min, max(montant) as max '.
1060                          'from '.$this->prefix.'TARIF where lie_ref = "'.$orsref['KOID'].'"'.
1061                          'and duree = "'.$this->prefix.'TYPEDUREETARIF:1" '.
1062                          'and lie like "'.$this->prefix.'CHAMBRE%"  and lang="'.TZR_DEFAULT_LANG.'" '.
1063                          'and libelle not like "%suppl%" and libelle not like "%P.SUP%"')
1064                          ->fetch();
1065      elseif ($orsref['type'] == $this->prefix.'TYPEPRODUIT:se' || $orsref['type'] == $this->prefix.'TYPEPRODUIT:gs' || $orsref['type'] == $this->prefix.'TYPEPRODUIT:ge')
1066        $ors = selectQuery('select montant as min, montant_maxi as max '.
1067                          'from '.$this->prefix.'TARIF where lie_ref = "'.$orsref['KOID'].'"'.
1068                          'and libelle = "PERS.NUIT"')
1069                          ->fetch();
1070      else // lie évite suppl
1071        $ors = selectQuery('select min(montant) as min, max(montant) as max '.
1072                           'from '.$this->prefix.'TARIF where lie = "'.$orsref['KOID'].'"'.
1073                           'and duree = "'.$this->prefix.'TYPEDUREETARIF:7"')
1074                           ->fetch();
1075      $ar['constarifmin'] = $ors['min'];
1076      $ar['constarifmax'] = $ors['max'];
1077    }
1078    // Animaux
1079    if (!empty($this->xset->desc['consani'])) {
1080      if (strpos($orsref['caracteristiques'], $this->animauxok)!==false) $ar['consani'] = 1;
1081      else $ar['consani'] = 2;
1082    }
1083    // Table d'hote
1084    if (!empty($this->xset->desc['constho'])) {
1085      if (strpos($orsref['caracteristiques'], $this->restook)!==false) $ar['constho'] = 1;
1086      else $ar['constho'] = 2;
1087    }
1088    // Album pho

Large files files are truncated, but you can click here to view the full file