/class.xmodwebresa.inc
PHP | 931 lines | 662 code | 81 blank | 188 comment | 62 complexity | c655b59d4349e4ade2721fdd05ab7e8e MD5 | raw file
Possible License(s): LGPL-2.0, LGPL-2.1, GPL-3.0, Apache-2.0, BSD-3-Clause
- <?php
- /**
- * File class.xmodwebresa.inc
- * Module d'interface générique avec webresa.fr
- * utilisation des flux standards de webresa
- *
- * \author Julien Guillaume <julien.guillaume@xsalto.com>
- * \version 0.1
- * Décembre 2012 pour seolan 8.1
- *
- */
- class XModWebresa extends XModTable {
- public $prefix = "WR_";
- public $needUpdate = false;
- public $versionInstalled = false;
- public $fluxurl = NULL;
- public $agenceid = NULL;
- public $codeflux = NULL;
- public $codesite = NULL;
- public $moidagences = NULL;
- public $moidattributs = NULL;
- public $moidpays = NULL;
- public $onlinebooking = false;
- public $onlinebookingurl = NULL;
- public $defaultSelectedFields = array('libelle','commentaire','prix_minimum','duree','niveau_oid');
- private $cachefile = NULL;
-
- function __construct($ar=NULL) {
- parent::__construct($ar);
- $this->cachefile = TZR_TMP_DIR.$this->_moid.'webresa.xml';
-
- /*
- if($this->interactive && XShell::admini_mode()){
- /// detection d'un nouveau schema dans le Wizard
- $currentversion = XDBIni::getStatic($this->_moid.'version','val');
- $this->versionInstalled = $currentversion;
- if( $currentversion != XModWebresaWd::version){
- setSessionVar('message', 'XModWebresa (moid:'.$this->_moid.') : Mise à jour disponible '.$currentversion." => ".XModWebresaWd::version);
- $this->needUpdate = true;
- }
- }
- */
- XLabels::loadLabels('xmodwebresa');
- }
- /**
- * Initialisation des propriétés
- */
- public function initOptions() {
- $genlabel=XLabels::getSysLabel('xmodule.general');
- XLabels::loadLabels('xmodwebresa');
- $labels = XLabels::$LABELS['xmodwebresa'];
- $configgrp = $labels['configgroup'];
- $configgrpasso = $labels['configgroupasso'];
-
- $this->_options->setOpt(XLabels::getSysLabel('general','version'),'versionInstalled','text',array('compulsory'=>true),NULL,$genlabel);
- $this->_options->setRO('versionInstalled');
- $this->_options->setOpt($labels['iptodeclare'],'ipsortante','text',array('compulsory'=>true),NULL,$genlabel);
- parent::initOptions();
- $this->_options->setOpt($labels['tableprefix'], 'prefix', 'text',NULL,NULL,$configgrp);
- $this->_options->setRO('prefix');
- $this->_options->setOpt($labels['fluxurl'], 'fluxurl', 'text',array('size'=>100),'http://www.webresa.fr/rss/getWebResaFlow.aspx?key=CODEFLUX&id=AGENCE&dest=SITE',$configgrp);
- $this->_options->setOpt($labels['agenceid'], 'agenceid', 'text',NULL,NULL,$configgrp);
- $this->_options->setOpt($labels['codeflux'], 'codeflux', 'list',array('labels'=>array($labels['codefluxall'],$labels['codefluxsite'],$labels['codefluxsiteextended']),'values'=>array('all_etendu','all_etendu_export','all_dates_etendu_export')),'all_etendu',$configgrp);
- $this->_options->setOpt($labels['codesite'], 'codesite', 'text',NULL,'',$configgrp);
- $this->_options->setOpt($labels['useiframe'], 'onlinebooking', 'boolean',NULL,'',$configgrp);
- $this->_options->setOpt($labels['moduleagence'], 'moidagences', 'module',NULL,'',$configgrpasso);
- $this->_options->setOpt($labels['moduleattributs'], 'moidattributs', 'module',NULL,'',$configgrpasso);
- $this->_options->setOpt($labels['modulepays'], 'moidpays', 'module',NULL,'',$configgrpasso);
- $this->_options->setOpt($labels['onlinebookingurl'], 'onlinebookingurl', 'text',array('size'=>100),'',$configgrp);
- }
- function secGroups($function, $group=NULL) {
- $g=array();
- $g['updateSchema'] = array('admin');
- $g['importFluxManual'] = array('admin');
- $g['importFluxCron'] = array('admin');
- $g['getTrekFromCache'] = array('admin');
- if(isset($g[$function])) {
- if(!empty($group)) return in_array($group, $g[$function]);
- return $g[$function];
- }
- return parent::secGroups($function,$group);
- }
- /// Listes des actions générales du module
- protected function _actionlist(&$my,$alfunction=true) {
- parent::_actionlist($my,$alfunction);
- $myclass=get_class($this);
- $moid=$this->_moid;
- // Suppression module
- if(/*$this->needUpdate && */$this->secure('','updateSchema') ){
- $o1=new XModuleAction($this,'updateSchema','Mettre à jour les tables & modules',
- '&moid='.$moid.'&_function=updateSchema&template=basic/message.html');
- $o1->needsconfirm=true;
- $my['updateSchema']=$o1;
- }
- }
- function getUIFunctionList() {
- $r = parent::getUIFunctionList();
- $r['reservation'] = 'Iframe de reservation';
- return $r;
- }
- function UIEdit_reservation($ar) {
- }
- function UIProcEdit_reservation($ar) {
- }
- function UIView_reservation($ar) {
- $ret = array('onlinebookingurl'=>$this->onlinebookingurl);
- return $ret;
- }
- public function UIEdit_procQuery($ar=NULL){
- if( empty($ar['__selectedfields']) ) $ar['__selectedfields'] = $this->defaultSelectedFields;
- return parent::UIEdit_procQuery($ar);
- }
- public function &UIView_procQuery($ar=NULL){
- if( empty($ar['__selectedfields']) ) $ar['__selectedfields'] = implode('||',$this->defaultSelectedFields);
- $ret = parent::UIView_procQuery($ar);
-
- //ajout des média
- foreach($ret['lines_oid'] as $key => $oid){
- $ret['lines_ssmod'][$key] = array('oid'=>$oid);
- $ars = array('ssmoid'=>$this->ssmod1);
- $this->setSubModules($ars, $ret['lines_ssmod'][$key]);
- }
- return $ret;
- }
- public function UIView_display($params) {
- if($this->onlinebooking){
- $params['__selectedfields'] .= '||urlIframeDate||url2IframeDate';
- }
- $ret = parent::UIView_display($params);
- $ret['onlinebookingurl'] = $this->onlinebookingurl;
- return $ret;
- }
- /**
- * Functions utilisé pour la synchronisation des données
- *
- *
- *
- */
-
- /**
- * Construit l'url du flux a partir des paramètre du module
- */
- public function constructFluxUrl(){
- if($this->fluxurl){
- $ret = str_replace(array('CODEFLUX','AGENCE','SITE'),array($this->codeflux,$this->agenceid,$this->codesite),$this->fluxurl);
- }
- return $ret;
- }
-
- /**
- * Retourne le contenu de l'url passé en paramètre
- * @return le contenu du flux ou False en cas d'erreur
- */
- private function _getFlux($url){
- $default_opts = array('http'=>array('method'=>"GET",
- 'timeout'=>80,
- 'header'=>"Accept-language: en\r\n" .
- "Cookie: foo=bar")
- );
- /// utiliser l'ip sortante configurer
- if($this->ipsortante)
- $default_opts['socket'] = array(
- 'bindto' => $this->ipsortante.':0'
- );
-
- $context = stream_context_create($default_opts);
- $ret = file_get_contents($url,false,$context);
- XDBIni::setStatic($this->_moid.'lastfluxurl',$url);
- XDBIni::setStatic($this->_moid.'lastfluxdate',date('Y-m-d H:m:s'));
- XDBIni::setStatic($this->_moid.'lastfluxheader',implode("\n",$http_response_header));
- return $ret;
- //pour analyser les header en retour : $http_response_header
- }
- /**
- * Controle que l'url existe et n'est pas vide (lenght>0)
- * @return l'url ou False en cas d'erreur
- */
- private function _getHttpRealFile($url){
- $default_opts = array('http'=>array('method'=>"GET",
- 'timeout'=>5,
- 'header'=>"Accept-language: en\r\n" .
- "Cookie: foo=bar"));
- $default = stream_context_create($default_opts);
- $header = get_headers($url,1);
- if(preg_match("/HTTP\/.* 200/" ,$header[0]) && $header['Content-Length'] > 0)
- return $url;
- else return false;
- }
-
- /**
- * récupère l'oid d'une agence a partir de son code
- * si l'agence n'existe pas on la crée validé par défaut
- * si elle existe mais non validé on retourne false
- * $code : code webresa de l'agence
- * $nom : libelle
- * $date : date de création du flux chez webresa
- * \return l'oid si trouvé false si non valide
- */
- private function _getAgenceOid($code,$nom,$date){
- $xmodagence = XModule::objectFactory($this->moidagences);
- $rs = selectQueryGetOne('SELECT * FROM '.$xmodagence->table.' WHERE code=\''.$code.'\'' );
- if($rs && $rs['KOID'] ){
- return ($rs['PUBLISH'] == 1)?$rs['KOID']:false;
- }else{
- $ins = array();
- $ins['code'] = $code;
- $ins['libelle'] = $nom;
- $ins['date_crea'] = $date;
- $ins['PUBLISH'] = 1;
- $insert = $xmodagence->procInsert($ins);
- return $insert['oid'];
- }
- }
- /**
- * récupère l'oid du pays
- * si le pays n'existe pas on le crée
- * sinon on ajoute l'agence au pays
- * si il existe mais non validé on retourne false
- * $nom : libelle
- * $agence : oid de l'agence
- * \return l'oid si trouvé false si non valide
- */
- private function _getPaysOid($nom,$agence){
- if(empty($nom)) return false;
- $xmodpays = XModule::objectFactory($this->moidpays);
- $cond = array( 'libelle'=>array('=',$nom) );
- $res = $xmodpays->browse(array('selectedfields'=>'all','tplentry'=>TZR_RETURN_DATA,'cond'=>$cond));
- if(count($res['lines_oid'])> 0 ){
- $agences = $res['lines_oagences'][0]->oidcollection;
- $agences[] = $agence;
- $xmodpays->procEdit(array('oid'=>$res['lines_oid'][0],'agences'=>array_unique($agences)));
- $ret = ($res['lines_oPUBLISH'][0]->raw==1)?$res['lines_oid'][0]:false;
- unset($xmodpays);
- return $ret;
- }elseif(count($res['lines_oid']) == 0){
- $insert = $xmodpays->procInsert(array('libelle'=>$nom,'agences'=>$agence,'PUBLISH'=>1));
- unset($xmodpays);
- return $insert['oid'];
- }
- }
- /**
- * Récupère l'oid de la rando à partir du trek_id
- */
- private function _getRando($trek_id){
- $sel = 'SELECT KOID FROM '.$this->table.' WHERE trek_id =\''.$trek_id.'\' AND LANG=\''.TZR_DEFAULT_LANG.'\'';
- $rs = selectQueryGetOne($sel);
- if($rs){
- return $this->display(array('oid'=>$rs['KOID'],'tplentry'=>TZR_RETURN_DATA));
- }else return false;
- }
- /** insert/met a jour une rando a partir de son trek_id
- * $ar : tableau à insérer
- * return oid si mise à jour ou inséré
- * false sinon
- */
- private function _insertUpdateRando($ar){
- $ar['_local'] = 1;
- $ar['_updateifexists'] = true;
- $ar['_unique'] = array('trek_id');
- return $this->xset->procInput($ar);
- }
- /** insert/met a jour une date de départ d'un séjour
- * $ar : tableau à insérer
- * return oid si mise à jour ou inséré
- * false sinon
- */
- private function _insertUpdateDepart($ar){
- $xmoddate = XModule::objectFactory($this->ssmod3);
- if(empty($xmoddate))
- return array('message'=>'Module Départ ('.$this->ssmod3.') inexistant');
- $ar['_local'] = 1;
- $ar['_updateifexists'] = true;
- $ar['_unique'] = array('treks_id','date_depart');
- return $xmoddate->xset->procInput($ar);
- }
- /** insert/met a jour un jour du programme d'un séjour
- * $ar : tableau à insérer
- * return oid si mise à jour ou inséré
- * false sinon
- */
- private function _insertUpdateProgramme($ar){
- $xmoddate = XModule::objectFactory($this->ssmod4);
- if(empty($xmoddate))
- return array('message'=>'Module Programme ('.$this->ssmod4.') inexistant');
- $ar['_local'] = 1;
- $ar['_updateifexists'] = true;
- $ar['_unique'] = array('treks_id','webresa_id');
- return $xmoddate->xset->procInput($ar);
- }
- /**
- * nettoye le programme
- * supprime pour un circuit les jours provennat de webresa qui ne sont plus dans le flux
- *
- */
- private function _cleanProgramme($trekoid,$oids){
- $xmodp = XModule::objectFactory($this->ssmod4);
- if(empty($xmodp))
- return false;
- $sel = 'DELETE FROM '. $xmodp->table .
- ' WHERE treks_id = \' '. $trekoid .'\' AND (webresa_id <> \'\' OR webresa_id IS NOT NULL) AND KOID NOT IN (\''.implode("','",$oids).'\')';
- selectQuery($sel);
- }
- /** insert/met a jour une rubrique ou fiche pratique
- * $ar : tableau à insérer
- * return oid si mise à jour ou inséré
- * false sinon
- */
- private function _insertUpdateRubrique($ar,$mod=5){
- $nummod = 'ssmod'.$mod;
- $xmoddate = XModule::objectFactory($this->$nummod);
- if(empty($xmoddate))
- return array('message'=>'Sous Module '.$mod.' ('.$this->$nummod.') inexistant');
- $ar['_local'] = 1;
- $ar['_updateifexists'] = true;
- $ar['_unique'] = array('treks_id','webresa_id');
- return $xmoddate->xset->procInput($ar);
- }
- /**
- * nettoye les rubriques
- *
- */
- private function _cleanRubriques($trekoid,$oids){
- $xmodp = XModule::objectFactory($this->ssmod5);
- if(empty($xmodp))
- return false;
- $sel = 'DELETE FROM '. $xmodp->table .
- ' WHERE treks_id = \' '. $trekoid .'\' AND (webresa_id <> \'\' OR webresa_id IS NOT NULL) AND KOID NOT IN (\''.implode("','",$oids).'\')';
- selectQuery($sel);
- $xmodp = XModule::objectFactory($this->ssmod6);
- $sel = 'DELETE FROM '. $xmodp->table .
- ' WHERE treks_id = \' '. $trekoid .'\' AND (webresa_id <> \'\' OR webresa_id IS NOT NULL) AND KOID NOT IN (\''.implode("','",$oids).'\')';
- selectQuery($sel);
- }
-
- /** invalide une rando
- * $oid
- * return oid si mise à jour ou inséré
- * false sinon
- */
- private function _unpublishRando($oid){
- $ar['_local'] = 1;
- $ar['value'] = 2;
- $ar['oid'] = $oid;
- return $this->xset->publish($ar);
- }
- /** retourne le soid console du mode fournit dans le flux
- * Vide ou Accompagné => accompagne
- * Liberté => liberte
- *
- */
- private function _setMode($mode){
- switch ($mode){
- case 'Liberté':
- return 'liberte';
- case '':
- case 'Accompagné':
- default:
- return 'accompagne';
- }
- }
- /** retourne le soid console de l'etat de la date
- * Vide => disponible
- * Confirmé => confirme
- * Annulé => annule
- * Complet => complet
- *
- */
- private function _setEtatDate($etat){
- switch ($etat){
- case 'Complet':
- return 'complet';
- case 'Annulé':
- return 'Annule';
- case 'Confirmé':
- return 'confirme';
- case '':
- default:
- return 'disponible';
- }
- }
- private function _setAttribut($str,$fieldname,$agence){
- $str = (string) $str;
- if($str == '') return false;
- $tb_typeAttr = array('type_oid'=>'typer',
- 'niveau_oid'=>'niveau',
- 'niveau_tech_oid'=>'niveau_tech',
- 'hebergements'=>'hebergement',
- 'themes'=>'theme',
- 'activite'=>'activite',
- 'portage'=>'portage'
- );
- $att_type = $tb_typeAttr[$fieldname];
- $xmodattr = XModule::objectFactory($this->moidattributs);
- if(empty($xmodattr))
- return false;
- $cond = array('libelle'=>array('=',$str));
- $cond['att_type'] = array('=',$att_type);
- $res = $xmodattr->browse(array('tplentry'=>TZR_RETURN_DATA,'cond'=>$cond,'selectedfields'=>'all'));
- if(count($res['lines_oid'])> 0 ){
- $ret = $res['lines_oid'][0];
- $agences = $res['lines_oagence'][0]->oidcollection;
- $agences[] = $agence;
- $xmodattr->xset->procEdit(array('oid'=>$res['lines_oid'][0],'agence'=>array_unique($agences)));
- return $ret;
- }elseif(count($res['lines_oid']) == 0){
- $res = $xmodattr->xset->procInput(array('libelle'=>$str,'agence'=>$agence,'att_type'=>$att_type));
- return $res['oid']?$res['oid']:false;
- }
- }
- /**
- * Mise à jour des départ pour le trek
- * \return tableau des oids mis à jour ou inséré
- */
- private function _updateDeparts($trekoid,DOMNodeList &$departs,DOMXPath &$xpath){
- $retOid = array();
- foreach($departs as $depart){
- $date= array();
- $date['treks_id'] = $trekoid;
- $date['PUBLISH'] = 1;
- $date['date_depart'] = $xpath->query('date',$depart)->item(0)->nodeValue;
- if($xpath->query('date_fin_sejour',$depart)->item(0)->nodeValue){
- $date['date_fin'] = $xpath->query('date_fin_sejour',$depart)->item(0)->nodeValue;
- }else{
- $datedts = strptime($date['date_depart'],"%Y-%m-%d");
- $date['date_fin'] = date('Y-m-d',mktime(12,0,0,$datedts['tm_mon']+1,$datedts['tm_mday']+$rando['NBJOUR']-1,1900+$datedts['tm_year']));
- }
- $date['prix'] = $this->_formatPrice($xpath->query('prix',$depart)->item(0)->nodeValue);
- $date['ancien_prix'] = $this->_formatPrice($xpath->query('ancien_prix',$depart)->item(0)->nodeValue);
-
- $date['etat'] = $this->_setEtatDate($xpath->query('etat',$depart)->item(0)->nodeValue);
- $date['disponibilite'] = $xpath->query('disponibilite',$depart)->item(0)->nodeValue;
- $date['capacite'] = $xpath->query('capacite',$depart)->item(0)->nodeValue;
- $date['resa'] = $xpath->query('resa',$depart)->item(0)->nodeValue;
- $date['place_option'] = $xpath->query('option',$depart)->item(0)->nodeValue;
- $res = $this->_insertUpdateDepart($date);
- if ($res['oid']) $retOid[] = $res['oid'];
-
- }
- return $retOid;
- }
- /**
- * invalide les element du sou module
- * $trekoid : oid de la rando
- * $oids : tableau des oid à ne pas invalidé
- */
- private function _unpublishSsmod($trekoid,$oids,$modnum=3/* depart */){
- $modkey = 'ssmod'.$modnum;
- if($modnum == 1 || $modnum == 2){ // medias
- $cpl = "AND source <> '' OR source IS NULL ";
- }elseif( $modnum > 3 ){ //chapitre
- $cpl = "AND webresa_id <> '' OR webresa_id IS NULL ";
- }
- $xmoddate = XModule::objectFactory($this->$modkey);
- $sel = 'UPDATE '.$xmoddate->table.' SET PUBLISH = 2 WHERE treks_id = \''.$trekoid.'\' AND KOID NOT IN (\''.implode("','",$oids).'\') '.$cpl;
- selectQuery($sel);
- }
- /**
- * Format un prix en entier (suppression de la virgule
- *
- */
- private function _formatPrice($str){
- return (float) str_replace(',','.',$str);
- }
- /**
- * Réparation du code html lavant insertion
- */
- function tidyRepair($txt){
- tidyString($txt);
- return $txt;
- }
- /**
- * Ajoute un media a un circuit si elle n'existe pas
- * $trek_id: oid du circuit
- * $url: url de l'image source
- * return oid du media si mise à jour ou inséré
- * false sinon
- */
- private function _addMediaRando($trek_id, $url, $type, $ordre){
- if(empty($url)) return;
- $xmodmedia = XModule::objectFactory($this->ssmod1);
- $ar= array();
- $ar['_local'] = 1;
- $ar['_updateifexists']=true;
- $ar['_unique'] = array('trek_id','source');
- $ar['treks_id'] = $trek_id;
-
- $ar['typem'] = $type;
- $ar['ordre'] = $ordre;
- $ar['media'] = $ar['source'] = str_replace(' ','%20',$url);
- //Est que l'image existe
- $cnt = countSelectQuery("select count(KOID) from {$xmodmedia->table} where source = '".$ar['source']."' AND treks_id = '".$ar['treks_id']."'");
- if( $cnt ){
- $ar['PUBLISH'] = 1;
- }
- $ret = $xmodmedia->xset->procInput($ar);
- return $ret['oid'];
- }
- /**
- * Function réalisant l'import des séjours depuis le flux
- * @return $message
- */
- function importFlux($ar=NULL) {
- $param = new XParam($ar,array());
- $fromcache = $param->get('fromcache');
- $cachefile = $this->cachefile;
- ini_set('max_execution_time',1500); /// le traitement peux être long ...
- try{
- /// Récupération du flux
- if($fromcache == 1 && file_exists($cachefile)){
- $mainFluxUrl = $cachefile;
- }else{
- $mainFluxUrl = $this->constructFluxUrl();
- }
- $mainFluxStream = $this->_getFlux($mainFluxUrl);
- if(!$mainFluxStream)
- throw new Exception("Flux $mainFluxUrl ne répond pas ");
- if($mainFluxUrl != $cachefile) /// Copier le fichier en local
- file_put_contents($cachefile,$mainFluxStream);
- ///construction du dom
- $dom = new DOMDocument();
- $dom->preserveWhiteSpace = false;
- $dom->loadXML($mainFluxStream);
- $xpath = new DOMXpath($dom);
-
- /// list des agences
- $agences = $xpath->query('//agence');
- $message .= $agences->length." agences found in the xml $mainFluxUrl\n";
- $tb_oidrando = array();///tableau des oids traités
- foreach ($agences as $agence) {
- $codeAgence = $xpath->query('infos/code',$agence)->item(0)->nodeValue;
- $nomAgence = $xpath->query('infos/libelle',$agence)->item(0)->nodeValue;
- $dateAgence = $xpath->query('infos/date',$agence)->item(0)->nodeValue;
- $oidAgence = $this->_getAgenceOid($codeAgence,$nomAgence,$dateAgence);
- if(!$oidAgence){ /// si l'agence n'est pas publié on n'import rien
- $nbcircuit = $treks->length;
- $message .= "Agence $nomAgence ($codeAgence) non trouvé dans vagabondages ($nbcircuit circuits)\n";
- continue;
- }
- /// parcours des treks de l'agence
- $tb_oidrando[$oidAgence] = array();
- $treks = $xpath->query('treks/trek',$agence);
- $message .= '- '.$nomAgence.' : '.$treks->length.' treks trouvé '."\n";
- foreach ($treks as $trek){
- $rando = array();
- $rando['agences_oid'] = $oidAgence;
- $rando['trek_id'] = $trek->attributes->getNamedItem("id")->nodeValue;
- $disp_rando = $this->_getRando($rando['trek_id']);
- ///si la mise à jour est interdite on ne fait rien
- if($disp_rando['onomaj']->raw == 1){
- $tb_oidrando[$oidAgence][] = $disp_rando['oid'];
- continue;
- }
- /// on vérifie que le pays est validé en console, si non on invalide la rando
- /// si le pays n'est pas remplit dans webresa le circuit ne sera pas remonté
- $oidPays = $this->_getPaysOid(strtolower($xpath->query('pays',$trek)->item(0)->nodeValue),$oidAgence);
- if(!$oidPays ){
- if($disp_rando['oid']) $this->_unpublishRando($disp_rando['oid']);
- continue;
- }
- ///si la rando n'existe pas on met le champ publié dans l'etat initial
- if(!$disp_rando['oid'])
- $rando['PUBLISH'] = $this->defaultispublished?1:2;
- $rando['pays'] = $oidPays;
- $rando['webresa_id'] = $xpath->query('uid',$trek)->item(0)->nodeValue;
- $rando['webresa_num'] = $xpath->query('numero',$trek)->item(0)->nodeValue;
- $rando['code'] = $xpath->query('code',$trek)->item(0)->nodeValue;
- $rando['href'] = $xpath->query('href',$trek)->item(0)->nodeValue;
- $rando['region'] = $xpath->query('region',$trek)->item(0)->nodeValue;
- $rando['mode'] = $this->_setMode($xpath->query('mode',$trek)->item(0)->nodeValue);
- $rando['libelle'] = $xpath->query('libelle',$trek)->item(0)->nodeValue;
- $rando['duree'] = $xpath->query('duree',$trek)->item(0)->nodeValue;
- $rando['duree_nuit'] = $xpath->query('duree_nuit',$trek)->item(0)->nodeValue;
- $rando['marche'] = $xpath->query('marche',$trek)->item(0)->nodeValue;
- $rando['type_oid'] = $this->_setAttribut($xpath->query('type',$trek)->item(0)->nodeValue,'type_oid',$oidAgence);
- $rando['niveau_oid'] = $this->_setAttribut($xpath->query('niveau',$trek)->item(0)->nodeValue,'niveau_oid',$oidAgence);
- $rando['niveau_tech_oid'] = $this->_setAttribut($xpath->query('niveau_tech',$trek)->item(0)->nodeValue,'niveau_tech_oid',$oidAgence);
- $hebergements = $xpath->query('hebergements/hebergement',$trek);
- $rando['hebergements'] = array();
- foreach($hebergements as $hebergement){
- $rando['hebergements'][] = $this->_setAttribut($hebergement->nodeValue,'hebergements',$oidAgence);
- }
- $rando['hebergements'] = array_unique($rando['hebergements']);
-
- $themes = $xpath->query('themes/theme',$trek);
- $rando['themes'] = array();
- foreach($themes as $theme){
- $rando['themes'][] = $this->_setAttribut($theme->nodeValue,'themes',$oidAgence);
- }
- $rando['themes'] = array_unique($rando['themes']);
-
- $rando['activite'] = $this->_setAttribut($xpath->query('activite',$trek)->item(0)->nodeValue,'activite',$oidAgence);
- $rando['portage'] = $this->_setAttribut($xpath->query('portage',$trek)->item(0)->nodeValue,'portage',$oidAgence);
- $rando['nb_jour_portage'] = $xpath->query('nb_jour_portage',$trek)->item(0)->nodeValue;
- $rando['circuit_exception'] = ($xpath->query('circuit_exception',$trek)->item(0)->nodeValue == 1 || $xpath->query('circuit_exception',$trek)->item(0)->nodeValue == 'oui' )?1:2;
- $rando['ville_depart'] = $xpath->query('ville_depart',$trek)->item(0)->nodeValue;
- $rando['ville_arrivee'] = $xpath->query('ville_arrivee',$trek)->item(0)->nodeValue;
- $rando['geoloc_depart'] = $this->degree2dec($xpath->query('latitude_depart',$trek)->item(0)->nodeValue).";".$this->degree2dec($xpath->query('longitude_depart',$trek)->item(0)->nodeValue);
- $rando['geoloc_arrivee'] = $this->degree2dec($xpath->query('latitude_arrivee',$trek)->item(0)->nodeValue).";".$this->degree2dec($xpath->query('longitude_arrivee',$trek)->item(0)->nodeValue);
- $rando['prix_minimum'] = $xpath->query('prix_minimum',$trek)->item(0)->nodeValue;
- $rando['prix_maximum'] = $xpath->query('prix_maximum',$trek)->item(0)->nodeValue;
- $rando['tel'] = $xpath->query('tel',$trek)->item(0)->nodeValue;
- $rando['commentaire'] = $xpath->query('commentaire',$trek)->item(0)->nodeValue;
- $rando['fiche_technique'] = $xpath->query('fiche_technique',$trek)->item(0)->nodeValue;
- ///insertion ou Mise a jour
- $resinsert = $this->_insertUpdateRando($rando);
- if(!$resinsert['oid']){
- $message .= "\t".$rando['trek_id'].' erreur d\'insertion'.$resinsert;
- continue;
- }else{
- $tb_oidrando[$oidAgence][] = $resinsert['oid'];
- }
-
- ///traitement des images
- $insertedmedia = array();
- $images = $xpath->query('images/image',$trek);
- $ordrei = 1;
- foreach($images as $image){
- $insertedmedia[] = $this->_addMediaRando($resinsert['oid'], $image->nodeValue, 'image', $ordrei);
- }
- ///traitement des pdf
- $pdfs = $xpath->query('pdfs/pdf',$trek);
- $ordrep = 1;
- foreach($pdfs as $pdf){
- $insertedmedia[] = $this->_addMediaRando($resinsert['oid'], $pdf->nodeValue, 'pdf', $ordrep);
- }
- $this->_unpublishSsmod($resinsert['oid'], $insertedmedia ,1);
- ///traitement des dates de departs
- $departs = $xpath->query('departs/depart',$trek);
- $oidsdate = $this->_updateDeparts($resinsert['oid'],$departs,$xpath);
- $this->_unpublishSsmod($resinsert['oid'],$oidsdate,3);
-
- ///traitement fiche technique
- if(!empty($rando['fiche_technique'])){
- $fichetech = new DOMDocument();
- $fichetech->preserveWhiteSpace = false;
- $fichetech->load($rando['fiche_technique']);
- $xpathft = new DOMXpath($fichetech);
-
- $randocpl = array();
- $randocpl['trek_id'] = $rando['trek_id'];
- $randocpl['auteur'] = $xpathft->query('/fiche/header/auteur')->item(0)->nodeValue;
-
- $randocpl['datePublication'] = $this->sqlDate( $xpathft->query('/fiche/header/datePublication')->item(0)->nodeValue,"%d/%m/%Y" );
- $randocpl['dateLastModification'] = $this->sqlDate( $xpathft->query('/fiche/header/dateLastModification')->item(0)->nodeValue,"%d/%m/%Y" );
- $randocpl['urlIframeDate'] = $xpathft->query('/fiche/header/urlIframeDates')->item(0)->nodeValue;
- $randocpl['url2IframeDate'] = $xpathft->query('/fiche/header/url2IframeDates')->item(0)->nodeValue;
- $randocpl['resume'] = $xpathft->query('/fiche/contenu/resume')->item(0)->nodeValue;
- $randocpl['complement'] = $xpathft->query("//chapitre[nomChapitre='PROGRAMME']/complementProgramme")->item(0)->nodeValue;
- $randocpl['libelle1'] = $xpathft->query('/fiche/contenu/sousTitre')->item(0)->nodeValue;
-
- $jours = $xpathft->query("//chapitre[nomChapitre='PROGRAMME']/jours/jour");
- $cntjour = 1;
- $idprogramme = array();
- foreach($jours as $jour){
- $prog = array();
- $prog['PUBLISH'] = 1;
- $prog['treks_id'] = $resinsert['oid'];
- $prog['ordre'] = $cntjour++;
- $prog['nom_jour'] = $xpathft->query("nomJour",$jour)->item(0)->nodeValue;
- $prog['description'] = $this->tidyRepair($xpathft->query("contenuJour",$jour)->item(0)->nodeValue);
- $idprogramme[] = $prog['webresa_id'] = $jour->attributes->getNamedItem("ID")->nodeValue;;
- $this->_insertUpdateProgramme($prog);
- }
- $rubriques = $xpathft->query("//chapitre[nomChapitre='FICHE PRATIQUE']/rubriques/rubrique");
- $cnt = 1;
- $idFiches = array();
- foreach($rubriques as $rubrique){
- $prog = array();
- $prog['PUBLISH'] = 1;
- $prog['treks_id'] = $resinsert['oid'];
- $prog['ordre'] = $cnt++;
- $prog['libelle'] = $xpathft->query("nomRubrique",$rubrique)->item(0)->nodeValue;
- $prog['description'] = $this->tidyRepair($xpathft->query("contenuRubrique",$rubrique)->item(0)->nodeValue);
- $idFiches[] = $prog['webresa_id'] = $rubrique->attributes->getNamedItem("ID")->nodeValue;;
- $this->_insertUpdateRubrique($prog,5);
- }
- $rubriques = $xpathft->query("//chapitreLibre");
- $cnt = 1;
- $idFiches = array();
- foreach($rubriques as $rubrique){
- $prog = array();
- $prog['PUBLISH'] = 1;
- $prog['treks_id'] = $resinsert['oid'];
- $prog['ordre'] = $cnt++;
- $prog['libelle'] = $xpathft->query("nomChapitreLibre",$rubrique)->item(0)->nodeValue;
- $prog['description'] = $this->tidyRepair($xpathft->query("contenuChapitreLibre",$rubrique)->item(0)->nodeValue);
- $idFiches[] = $prog['webresa_id'] = $rubrique->attributes->getNamedItem("ID")->nodeValue;;
- $this->_insertUpdateRubrique($prog,6);
- }
-
- $this->_cleanRubriques($resinsert['oid'],$idFiches);
- $resinsert = $this->_insertUpdateRando($randocpl);
- }
- unset($rando);
- if($param->get('getOne'))
- die($message);
- }
- }
-
- XLogs::notice('Webresa synchro',$message);
- return $message;
- }catch(Exception $e){
- XLogs::critical('Webresa synchro',$message);
- return 'Erreur found:'.$message.$e->getMessage();
- }
- }
-
- /**
- Appel manuel de la fonction d'import
- \return message de log a l'ecran
- */
- function importFluxManual($ar=NULL) {
- die(nl2br($this->importFlux($ar)));
- }
- /**
- Appel planifié de la fonction d'import
- \return message dans la cron
- */
- function importFluxCron(XModScheduler &$s, $o, $arraymore) {
- $mess = $this->importFlux($ar);
-
- $s->setStatusJob($o->KOID, 'finished', $mess);
- }
-
- /**
- Appel manuel de la fonction d'import
- \return message de log a l'ecran
- */
- function getTrekFromCache($ar=NULL) {
- $param = new XParam($ar,array());
- $cachefile = $this->cachefile;
- $id = $param->get('trek_id');
- ini_set('max_execution_time',1500); /// le traitement peux être long ...
- try{
- /// Récupération du flux
- $mainFluxUrl = $cachefile;
- $mainFluxStream = $this->_getFlux($mainFluxUrl);
- if(!$mainFluxStream)
- throw new Exception("Flux $mainFluxUrl ne répond pas ");
- ///construction du dom
- $dom = new DOMDocument();
- $dom->preserveWhiteSpace = false;
- $dom->loadXML($mainFluxStream);
- $xpath = new DOMXpath($dom);
-
- $treks = $xpath->query("//trek[@id='$id']");
- foreach($treks as $trek){
- header ("Content-Type:text/xml");
- die($trek->C14N());
- }
- }catch(Exception $e){
- die('Erreur found:'.$message.$e->message);
- }
- }
- /**
- * Groupe de Functions utilisés par la gestion du module
- * - Mise à jour
- * - supression
- *
- */
- public function updateSchema($ar){
- $mess = XModWebresaWd::updateSchema($this->prefix);
- $mess .= XModWebresaWd::updateProperties($this);
- $mess .= XModWebresaWd::addTemplates($this);
- XDBIni::setStatic($this->_moid.'version',XModWebresaWd::version);
- XShell::toScreen2('','message',$mess);
- }
- /**
- * Liste des tables utilisées par le module
- */
- public function usedTables() {
- $schematable = XModWebresaWd::getSchemaTables();
- $tables = array();
- foreach($schematable as $key => $tabledef){
- if ($key>0 && $tabledef[0])
- $tables[] = $this->prefix.$tabledef[0];
- }
- return $tables;
- }
- /**
- * Liste des tables principales du module
- */
- public function usedMainTables() {
- return array($this->table);
- }
- /**
- * Suppression du module et modules associés
- */
- function delete($ar) {
- //Module associé
- $modules = array($this->moidagences,$this->moidattributs,$this->moidpays,$this->ssmod1,$this->ssmod2,$this->ssmod3,$this->ssmod4,$this->ssmod4,$this->ssmod4);
- foreach($modules as $km=>$moid){
- if($moid && XModule::moduleExists($moid) ){
- $mod = XModule::objectFactory($moid);
- $ar1['withtable'] = false;
- $message .= $mod->delete($ar1)."\n";
- XModule::clearCache();
- }
- }
- $message .= parent::delete($ar);
- return XShell::toScreen2($tplentry,'message',$message);
- }
- /**
- * Page d'information du module
- */
- function getInfos($ar=NULL){
- $p=new XParam($ar,array('tplentry'=>TZR_RETURN_DATA));
- $tplentry=$p->get('tplentry');
- $ar['tplentry']=TZR_RETURN_DATA;
- $ret=parent::getInfos($ar);
- unset($ret['infos']['size']);
-
-
- $ret['infos']['version']->label = 'Version du schema';
- $currentversion = XDBIni::getStatic($this->_moid.'version','val');
- $ret['infos']['version']->html = $currentversion;
- $ret['infos']['lastfluxurl']->label = 'Url du dernier fluw analysé';
- $ret['infos']['lastfluxurl']->html = XDBIni::getStatic($this->_moid.'lastfluxurl','val');
- $ret['infos']['lastfluxdate']->label = 'Date de la dernière analyse';
- $ret['infos']['lastfluxdate']->html = XDBIni::getStatic($this->_moid.'lastfluxdate','val');
- $ret['infos']['lastfluxheader']->label = 'header de la réponse lors de la dernière analyse';
- $ret['infos']['lastfluxheader']->html = nl2br(XDBIni::getStatic($this->_moid.'lastfluxheader','val'));
- return XShell::toScreen1($tplentry,$ret);
- }
-
- function degree2dec($str){
- if(!$str) return false;
- $tmp = preg_split("/[°'\"]{1,2}/",$str,NULL,PREG_SPLIT_NO_EMPTY);
- $deg = (integer)$tmp[0];
- $min = (integer)$tmp[1];
- $sec = (integer)$tmp[2];
- $res = $deg + ((($sec/60)+$min)/60);
- return $res;
- }
- function alphatosqldate($str){
- $tb = explode('.',$str);
- return $tb[2].'-'.$tb[1].'-'.$tb[0];
- }
- function sqlDate($str,$fmt="%d/%m/%Y %H:%M:%S"){
- if(empty($str)) return '';
- $ar = strptime($str,$fmt);
- return date('Y-m-d',mktime(12,0,0,$ar['tm_mon']+1,$ar['tm_mday'],1900+$ar['tm_year']));
- }
- //retourn le nombre de jour entre 2 date
- function diffDate($d1,$d2){
- $ar1 = strptime($d2,"%Y-%m-%d");
- $ar2 = strptime($d1,"%Y-%m-%d");
- $diffs = mktime(12,0,0,$ar1['tm_mon']+1,$ar1['tm_mday'],1900+$ar1['tm_year'])-mktime(12,0,0,$ar2['tm_mon']+1,$ar2['tm_mday'],1900+$ar2['tm_year']);
- return round($diffs/60/60/24);
- }
-
- /**
- * Creation automatique de la tâche
- *
- */
- public function chk($ar=NULL) {
- $this->_createTask($ar);
- return parent::chk($ar);
- }
- protected function _createTask($ar){
- $cnt = countSelectQuery("select count(*) from TASKS where amoid='".$this->_moid."' and status='cron' ");
- if(!$cnt) {
- $pc=array();
- $pc['title'] = $this->modulename.' - Import Flux';
- $pc['ptime'] = 'today';
- $pc['more'] = '<?xml version="1.0" encoding="utf-8"?><tzrdata v="1"><table><tr><th>class</th><td>XModWebresa</td></tr><tr><th>function</th><td>importFluxCron</td></tr><tr><th>moid</th><td>'.$this->_moid.'</td></tr><tr><th>uid</th><td>root</td></tr></table></tzrdata>';
- $pc['status'] = 'cron';
- $pc['amoid'] = $this->_moid;
- $pc['cron'] = '<?xml version="1.0" encoding="utf-8"?><tzrdata v="1"><table><tr><th>period</th><td>daily</td></tr><tr><th>freq</th><td>*/4</td></tr></table></tzrdata>';
- $pc['tplentry'] = TZR_RETURN_DATA;
- $xs = XDataSource::objectFactoryHelper8('BCLASS=XDSTable&SPECS=TASKS');
- $r1 = $xs->procInput($pc);
- $m = XLabels::getSysLabel('xmodwebresa','task_missing');
- XShell::toScreen2('','message',$m);
- }
- }
- }
- ?>