PageRenderTime 68ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 1ms

/class.xmodwebresa.inc

https://github.com/jcplat/console-seolan
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
  1. <?php
  2. /**
  3. * File class.xmodwebresa.inc
  4. * Module d'interface générique avec webresa.fr
  5. * utilisation des flux standards de webresa
  6. *
  7. * \author Julien Guillaume <julien.guillaume@xsalto.com>
  8. * \version 0.1
  9. * Décembre 2012 pour seolan 8.1
  10. *
  11. */
  12. class XModWebresa extends XModTable {
  13. public $prefix = "WR_";
  14. public $needUpdate = false;
  15. public $versionInstalled = false;
  16. public $fluxurl = NULL;
  17. public $agenceid = NULL;
  18. public $codeflux = NULL;
  19. public $codesite = NULL;
  20. public $moidagences = NULL;
  21. public $moidattributs = NULL;
  22. public $moidpays = NULL;
  23. public $onlinebooking = false;
  24. public $onlinebookingurl = NULL;
  25. public $defaultSelectedFields = array('libelle','commentaire','prix_minimum','duree','niveau_oid');
  26. private $cachefile = NULL;
  27. function __construct($ar=NULL) {
  28. parent::__construct($ar);
  29. $this->cachefile = TZR_TMP_DIR.$this->_moid.'webresa.xml';
  30. /*
  31. if($this->interactive && XShell::admini_mode()){
  32. /// detection d'un nouveau schema dans le Wizard
  33. $currentversion = XDBIni::getStatic($this->_moid.'version','val');
  34. $this->versionInstalled = $currentversion;
  35. if( $currentversion != XModWebresaWd::version){
  36. setSessionVar('message', 'XModWebresa (moid:'.$this->_moid.') : Mise à jour disponible '.$currentversion." => ".XModWebresaWd::version);
  37. $this->needUpdate = true;
  38. }
  39. }
  40. */
  41. XLabels::loadLabels('xmodwebresa');
  42. }
  43. /**
  44. * Initialisation des propriétés
  45. */
  46. public function initOptions() {
  47. $genlabel=XLabels::getSysLabel('xmodule.general');
  48. XLabels::loadLabels('xmodwebresa');
  49. $labels = XLabels::$LABELS['xmodwebresa'];
  50. $configgrp = $labels['configgroup'];
  51. $configgrpasso = $labels['configgroupasso'];
  52. $this->_options->setOpt(XLabels::getSysLabel('general','version'),'versionInstalled','text',array('compulsory'=>true),NULL,$genlabel);
  53. $this->_options->setRO('versionInstalled');
  54. $this->_options->setOpt($labels['iptodeclare'],'ipsortante','text',array('compulsory'=>true),NULL,$genlabel);
  55. parent::initOptions();
  56. $this->_options->setOpt($labels['tableprefix'], 'prefix', 'text',NULL,NULL,$configgrp);
  57. $this->_options->setRO('prefix');
  58. $this->_options->setOpt($labels['fluxurl'], 'fluxurl', 'text',array('size'=>100),'http://www.webresa.fr/rss/getWebResaFlow.aspx?key=CODEFLUX&id=AGENCE&dest=SITE',$configgrp);
  59. $this->_options->setOpt($labels['agenceid'], 'agenceid', 'text',NULL,NULL,$configgrp);
  60. $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);
  61. $this->_options->setOpt($labels['codesite'], 'codesite', 'text',NULL,'',$configgrp);
  62. $this->_options->setOpt($labels['useiframe'], 'onlinebooking', 'boolean',NULL,'',$configgrp);
  63. $this->_options->setOpt($labels['moduleagence'], 'moidagences', 'module',NULL,'',$configgrpasso);
  64. $this->_options->setOpt($labels['moduleattributs'], 'moidattributs', 'module',NULL,'',$configgrpasso);
  65. $this->_options->setOpt($labels['modulepays'], 'moidpays', 'module',NULL,'',$configgrpasso);
  66. $this->_options->setOpt($labels['onlinebookingurl'], 'onlinebookingurl', 'text',array('size'=>100),'',$configgrp);
  67. }
  68. function secGroups($function, $group=NULL) {
  69. $g=array();
  70. $g['updateSchema'] = array('admin');
  71. $g['importFluxManual'] = array('admin');
  72. $g['importFluxCron'] = array('admin');
  73. $g['getTrekFromCache'] = array('admin');
  74. if(isset($g[$function])) {
  75. if(!empty($group)) return in_array($group, $g[$function]);
  76. return $g[$function];
  77. }
  78. return parent::secGroups($function,$group);
  79. }
  80. /// Listes des actions générales du module
  81. protected function _actionlist(&$my,$alfunction=true) {
  82. parent::_actionlist($my,$alfunction);
  83. $myclass=get_class($this);
  84. $moid=$this->_moid;
  85. // Suppression module
  86. if(/*$this->needUpdate && */$this->secure('','updateSchema') ){
  87. $o1=new XModuleAction($this,'updateSchema','Mettre à jour les tables & modules',
  88. '&moid='.$moid.'&_function=updateSchema&template=basic/message.html');
  89. $o1->needsconfirm=true;
  90. $my['updateSchema']=$o1;
  91. }
  92. }
  93. function getUIFunctionList() {
  94. $r = parent::getUIFunctionList();
  95. $r['reservation'] = 'Iframe de reservation';
  96. return $r;
  97. }
  98. function UIEdit_reservation($ar) {
  99. }
  100. function UIProcEdit_reservation($ar) {
  101. }
  102. function UIView_reservation($ar) {
  103. $ret = array('onlinebookingurl'=>$this->onlinebookingurl);
  104. return $ret;
  105. }
  106. public function UIEdit_procQuery($ar=NULL){
  107. if( empty($ar['__selectedfields']) ) $ar['__selectedfields'] = $this->defaultSelectedFields;
  108. return parent::UIEdit_procQuery($ar);
  109. }
  110. public function &UIView_procQuery($ar=NULL){
  111. if( empty($ar['__selectedfields']) ) $ar['__selectedfields'] = implode('||',$this->defaultSelectedFields);
  112. $ret = parent::UIView_procQuery($ar);
  113. //ajout des média
  114. foreach($ret['lines_oid'] as $key => $oid){
  115. $ret['lines_ssmod'][$key] = array('oid'=>$oid);
  116. $ars = array('ssmoid'=>$this->ssmod1);
  117. $this->setSubModules($ars, $ret['lines_ssmod'][$key]);
  118. }
  119. return $ret;
  120. }
  121. public function UIView_display($params) {
  122. if($this->onlinebooking){
  123. $params['__selectedfields'] .= '||urlIframeDate||url2IframeDate';
  124. }
  125. $ret = parent::UIView_display($params);
  126. $ret['onlinebookingurl'] = $this->onlinebookingurl;
  127. return $ret;
  128. }
  129. /**
  130. * Functions utilisé pour la synchronisation des données
  131. *
  132. *
  133. *
  134. */
  135. /**
  136. * Construit l'url du flux a partir des paramètre du module
  137. */
  138. public function constructFluxUrl(){
  139. if($this->fluxurl){
  140. $ret = str_replace(array('CODEFLUX','AGENCE','SITE'),array($this->codeflux,$this->agenceid,$this->codesite),$this->fluxurl);
  141. }
  142. return $ret;
  143. }
  144. /**
  145. * Retourne le contenu de l'url passé en paramètre
  146. * @return le contenu du flux ou False en cas d'erreur
  147. */
  148. private function _getFlux($url){
  149. $default_opts = array('http'=>array('method'=>"GET",
  150. 'timeout'=>80,
  151. 'header'=>"Accept-language: en\r\n" .
  152. "Cookie: foo=bar")
  153. );
  154. /// utiliser l'ip sortante configurer
  155. if($this->ipsortante)
  156. $default_opts['socket'] = array(
  157. 'bindto' => $this->ipsortante.':0'
  158. );
  159. $context = stream_context_create($default_opts);
  160. $ret = file_get_contents($url,false,$context);
  161. XDBIni::setStatic($this->_moid.'lastfluxurl',$url);
  162. XDBIni::setStatic($this->_moid.'lastfluxdate',date('Y-m-d H:m:s'));
  163. XDBIni::setStatic($this->_moid.'lastfluxheader',implode("\n",$http_response_header));
  164. return $ret;
  165. //pour analyser les header en retour : $http_response_header
  166. }
  167. /**
  168. * Controle que l'url existe et n'est pas vide (lenght>0)
  169. * @return l'url ou False en cas d'erreur
  170. */
  171. private function _getHttpRealFile($url){
  172. $default_opts = array('http'=>array('method'=>"GET",
  173. 'timeout'=>5,
  174. 'header'=>"Accept-language: en\r\n" .
  175. "Cookie: foo=bar"));
  176. $default = stream_context_create($default_opts);
  177. $header = get_headers($url,1);
  178. if(preg_match("/HTTP\/.* 200/" ,$header[0]) && $header['Content-Length'] > 0)
  179. return $url;
  180. else return false;
  181. }
  182. /**
  183. * récupère l'oid d'une agence a partir de son code
  184. * si l'agence n'existe pas on la crée validé par défaut
  185. * si elle existe mais non validé on retourne false
  186. * $code : code webresa de l'agence
  187. * $nom : libelle
  188. * $date : date de création du flux chez webresa
  189. * \return l'oid si trouvé false si non valide
  190. */
  191. private function _getAgenceOid($code,$nom,$date){
  192. $xmodagence = XModule::objectFactory($this->moidagences);
  193. $rs = selectQueryGetOne('SELECT * FROM '.$xmodagence->table.' WHERE code=\''.$code.'\'' );
  194. if($rs && $rs['KOID'] ){
  195. return ($rs['PUBLISH'] == 1)?$rs['KOID']:false;
  196. }else{
  197. $ins = array();
  198. $ins['code'] = $code;
  199. $ins['libelle'] = $nom;
  200. $ins['date_crea'] = $date;
  201. $ins['PUBLISH'] = 1;
  202. $insert = $xmodagence->procInsert($ins);
  203. return $insert['oid'];
  204. }
  205. }
  206. /**
  207. * récupère l'oid du pays
  208. * si le pays n'existe pas on le crée
  209. * sinon on ajoute l'agence au pays
  210. * si il existe mais non validé on retourne false
  211. * $nom : libelle
  212. * $agence : oid de l'agence
  213. * \return l'oid si trouvé false si non valide
  214. */
  215. private function _getPaysOid($nom,$agence){
  216. if(empty($nom)) return false;
  217. $xmodpays = XModule::objectFactory($this->moidpays);
  218. $cond = array( 'libelle'=>array('=',$nom) );
  219. $res = $xmodpays->browse(array('selectedfields'=>'all','tplentry'=>TZR_RETURN_DATA,'cond'=>$cond));
  220. if(count($res['lines_oid'])> 0 ){
  221. $agences = $res['lines_oagences'][0]->oidcollection;
  222. $agences[] = $agence;
  223. $xmodpays->procEdit(array('oid'=>$res['lines_oid'][0],'agences'=>array_unique($agences)));
  224. $ret = ($res['lines_oPUBLISH'][0]->raw==1)?$res['lines_oid'][0]:false;
  225. unset($xmodpays);
  226. return $ret;
  227. }elseif(count($res['lines_oid']) == 0){
  228. $insert = $xmodpays->procInsert(array('libelle'=>$nom,'agences'=>$agence,'PUBLISH'=>1));
  229. unset($xmodpays);
  230. return $insert['oid'];
  231. }
  232. }
  233. /**
  234. * Récupère l'oid de la rando à partir du trek_id
  235. */
  236. private function _getRando($trek_id){
  237. $sel = 'SELECT KOID FROM '.$this->table.' WHERE trek_id =\''.$trek_id.'\' AND LANG=\''.TZR_DEFAULT_LANG.'\'';
  238. $rs = selectQueryGetOne($sel);
  239. if($rs){
  240. return $this->display(array('oid'=>$rs['KOID'],'tplentry'=>TZR_RETURN_DATA));
  241. }else return false;
  242. }
  243. /** insert/met a jour une rando a partir de son trek_id
  244. * $ar : tableau à insérer
  245. * return oid si mise à jour ou inséré
  246. * false sinon
  247. */
  248. private function _insertUpdateRando($ar){
  249. $ar['_local'] = 1;
  250. $ar['_updateifexists'] = true;
  251. $ar['_unique'] = array('trek_id');
  252. return $this->xset->procInput($ar);
  253. }
  254. /** insert/met a jour une date de départ d'un séjour
  255. * $ar : tableau à insérer
  256. * return oid si mise à jour ou inséré
  257. * false sinon
  258. */
  259. private function _insertUpdateDepart($ar){
  260. $xmoddate = XModule::objectFactory($this->ssmod3);
  261. if(empty($xmoddate))
  262. return array('message'=>'Module Départ ('.$this->ssmod3.') inexistant');
  263. $ar['_local'] = 1;
  264. $ar['_updateifexists'] = true;
  265. $ar['_unique'] = array('treks_id','date_depart');
  266. return $xmoddate->xset->procInput($ar);
  267. }
  268. /** insert/met a jour un jour du programme d'un séjour
  269. * $ar : tableau à insérer
  270. * return oid si mise à jour ou inséré
  271. * false sinon
  272. */
  273. private function _insertUpdateProgramme($ar){
  274. $xmoddate = XModule::objectFactory($this->ssmod4);
  275. if(empty($xmoddate))
  276. return array('message'=>'Module Programme ('.$this->ssmod4.') inexistant');
  277. $ar['_local'] = 1;
  278. $ar['_updateifexists'] = true;
  279. $ar['_unique'] = array('treks_id','webresa_id');
  280. return $xmoddate->xset->procInput($ar);
  281. }
  282. /**
  283. * nettoye le programme
  284. * supprime pour un circuit les jours provennat de webresa qui ne sont plus dans le flux
  285. *
  286. */
  287. private function _cleanProgramme($trekoid,$oids){
  288. $xmodp = XModule::objectFactory($this->ssmod4);
  289. if(empty($xmodp))
  290. return false;
  291. $sel = 'DELETE FROM '. $xmodp->table .
  292. ' WHERE treks_id = \' '. $trekoid .'\' AND (webresa_id <> \'\' OR webresa_id IS NOT NULL) AND KOID NOT IN (\''.implode("','",$oids).'\')';
  293. selectQuery($sel);
  294. }
  295. /** insert/met a jour une rubrique ou fiche pratique
  296. * $ar : tableau à insérer
  297. * return oid si mise à jour ou inséré
  298. * false sinon
  299. */
  300. private function _insertUpdateRubrique($ar,$mod=5){
  301. $nummod = 'ssmod'.$mod;
  302. $xmoddate = XModule::objectFactory($this->$nummod);
  303. if(empty($xmoddate))
  304. return array('message'=>'Sous Module '.$mod.' ('.$this->$nummod.') inexistant');
  305. $ar['_local'] = 1;
  306. $ar['_updateifexists'] = true;
  307. $ar['_unique'] = array('treks_id','webresa_id');
  308. return $xmoddate->xset->procInput($ar);
  309. }
  310. /**
  311. * nettoye les rubriques
  312. *
  313. */
  314. private function _cleanRubriques($trekoid,$oids){
  315. $xmodp = XModule::objectFactory($this->ssmod5);
  316. if(empty($xmodp))
  317. return false;
  318. $sel = 'DELETE FROM '. $xmodp->table .
  319. ' WHERE treks_id = \' '. $trekoid .'\' AND (webresa_id <> \'\' OR webresa_id IS NOT NULL) AND KOID NOT IN (\''.implode("','",$oids).'\')';
  320. selectQuery($sel);
  321. $xmodp = XModule::objectFactory($this->ssmod6);
  322. $sel = 'DELETE FROM '. $xmodp->table .
  323. ' WHERE treks_id = \' '. $trekoid .'\' AND (webresa_id <> \'\' OR webresa_id IS NOT NULL) AND KOID NOT IN (\''.implode("','",$oids).'\')';
  324. selectQuery($sel);
  325. }
  326. /** invalide une rando
  327. * $oid
  328. * return oid si mise à jour ou inséré
  329. * false sinon
  330. */
  331. private function _unpublishRando($oid){
  332. $ar['_local'] = 1;
  333. $ar['value'] = 2;
  334. $ar['oid'] = $oid;
  335. return $this->xset->publish($ar);
  336. }
  337. /** retourne le soid console du mode fournit dans le flux
  338. * Vide ou Accompagné => accompagne
  339. * Liberté => liberte
  340. *
  341. */
  342. private function _setMode($mode){
  343. switch ($mode){
  344. case 'Liberté':
  345. return 'liberte';
  346. case '':
  347. case 'Accompagné':
  348. default:
  349. return 'accompagne';
  350. }
  351. }
  352. /** retourne le soid console de l'etat de la date
  353. * Vide => disponible
  354. * Confirmé => confirme
  355. * Annulé => annule
  356. * Complet => complet
  357. *
  358. */
  359. private function _setEtatDate($etat){
  360. switch ($etat){
  361. case 'Complet':
  362. return 'complet';
  363. case 'Annulé':
  364. return 'Annule';
  365. case 'Confirmé':
  366. return 'confirme';
  367. case '':
  368. default:
  369. return 'disponible';
  370. }
  371. }
  372. private function _setAttribut($str,$fieldname,$agence){
  373. $str = (string) $str;
  374. if($str == '') return false;
  375. $tb_typeAttr = array('type_oid'=>'typer',
  376. 'niveau_oid'=>'niveau',
  377. 'niveau_tech_oid'=>'niveau_tech',
  378. 'hebergements'=>'hebergement',
  379. 'themes'=>'theme',
  380. 'activite'=>'activite',
  381. 'portage'=>'portage'
  382. );
  383. $att_type = $tb_typeAttr[$fieldname];
  384. $xmodattr = XModule::objectFactory($this->moidattributs);
  385. if(empty($xmodattr))
  386. return false;
  387. $cond = array('libelle'=>array('=',$str));
  388. $cond['att_type'] = array('=',$att_type);
  389. $res = $xmodattr->browse(array('tplentry'=>TZR_RETURN_DATA,'cond'=>$cond,'selectedfields'=>'all'));
  390. if(count($res['lines_oid'])> 0 ){
  391. $ret = $res['lines_oid'][0];
  392. $agences = $res['lines_oagence'][0]->oidcollection;
  393. $agences[] = $agence;
  394. $xmodattr->xset->procEdit(array('oid'=>$res['lines_oid'][0],'agence'=>array_unique($agences)));
  395. return $ret;
  396. }elseif(count($res['lines_oid']) == 0){
  397. $res = $xmodattr->xset->procInput(array('libelle'=>$str,'agence'=>$agence,'att_type'=>$att_type));
  398. return $res['oid']?$res['oid']:false;
  399. }
  400. }
  401. /**
  402. * Mise à jour des départ pour le trek
  403. * \return tableau des oids mis à jour ou inséré
  404. */
  405. private function _updateDeparts($trekoid,DOMNodeList &$departs,DOMXPath &$xpath){
  406. $retOid = array();
  407. foreach($departs as $depart){
  408. $date= array();
  409. $date['treks_id'] = $trekoid;
  410. $date['PUBLISH'] = 1;
  411. $date['date_depart'] = $xpath->query('date',$depart)->item(0)->nodeValue;
  412. if($xpath->query('date_fin_sejour',$depart)->item(0)->nodeValue){
  413. $date['date_fin'] = $xpath->query('date_fin_sejour',$depart)->item(0)->nodeValue;
  414. }else{
  415. $datedts = strptime($date['date_depart'],"%Y-%m-%d");
  416. $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']));
  417. }
  418. $date['prix'] = $this->_formatPrice($xpath->query('prix',$depart)->item(0)->nodeValue);
  419. $date['ancien_prix'] = $this->_formatPrice($xpath->query('ancien_prix',$depart)->item(0)->nodeValue);
  420. $date['etat'] = $this->_setEtatDate($xpath->query('etat',$depart)->item(0)->nodeValue);
  421. $date['disponibilite'] = $xpath->query('disponibilite',$depart)->item(0)->nodeValue;
  422. $date['capacite'] = $xpath->query('capacite',$depart)->item(0)->nodeValue;
  423. $date['resa'] = $xpath->query('resa',$depart)->item(0)->nodeValue;
  424. $date['place_option'] = $xpath->query('option',$depart)->item(0)->nodeValue;
  425. $res = $this->_insertUpdateDepart($date);
  426. if ($res['oid']) $retOid[] = $res['oid'];
  427. }
  428. return $retOid;
  429. }
  430. /**
  431. * invalide les element du sou module
  432. * $trekoid : oid de la rando
  433. * $oids : tableau des oid à ne pas invalidé
  434. */
  435. private function _unpublishSsmod($trekoid,$oids,$modnum=3/* depart */){
  436. $modkey = 'ssmod'.$modnum;
  437. if($modnum == 1 || $modnum == 2){ // medias
  438. $cpl = "AND source <> '' OR source IS NULL ";
  439. }elseif( $modnum > 3 ){ //chapitre
  440. $cpl = "AND webresa_id <> '' OR webresa_id IS NULL ";
  441. }
  442. $xmoddate = XModule::objectFactory($this->$modkey);
  443. $sel = 'UPDATE '.$xmoddate->table.' SET PUBLISH = 2 WHERE treks_id = \''.$trekoid.'\' AND KOID NOT IN (\''.implode("','",$oids).'\') '.$cpl;
  444. selectQuery($sel);
  445. }
  446. /**
  447. * Format un prix en entier (suppression de la virgule
  448. *
  449. */
  450. private function _formatPrice($str){
  451. return (float) str_replace(',','.',$str);
  452. }
  453. /**
  454. * Réparation du code html lavant insertion
  455. */
  456. function tidyRepair($txt){
  457. tidyString($txt);
  458. return $txt;
  459. }
  460. /**
  461. * Ajoute un media a un circuit si elle n'existe pas
  462. * $trek_id: oid du circuit
  463. * $url: url de l'image source
  464. * return oid du media si mise à jour ou inséré
  465. * false sinon
  466. */
  467. private function _addMediaRando($trek_id, $url, $type, $ordre){
  468. if(empty($url)) return;
  469. $xmodmedia = XModule::objectFactory($this->ssmod1);
  470. $ar= array();
  471. $ar['_local'] = 1;
  472. $ar['_updateifexists']=true;
  473. $ar['_unique'] = array('trek_id','source');
  474. $ar['treks_id'] = $trek_id;
  475. $ar['typem'] = $type;
  476. $ar['ordre'] = $ordre;
  477. $ar['media'] = $ar['source'] = str_replace(' ','%20',$url);
  478. //Est que l'image existe
  479. $cnt = countSelectQuery("select count(KOID) from {$xmodmedia->table} where source = '".$ar['source']."' AND treks_id = '".$ar['treks_id']."'");
  480. if( $cnt ){
  481. $ar['PUBLISH'] = 1;
  482. }
  483. $ret = $xmodmedia->xset->procInput($ar);
  484. return $ret['oid'];
  485. }
  486. /**
  487. * Function réalisant l'import des séjours depuis le flux
  488. * @return $message
  489. */
  490. function importFlux($ar=NULL) {
  491. $param = new XParam($ar,array());
  492. $fromcache = $param->get('fromcache');
  493. $cachefile = $this->cachefile;
  494. ini_set('max_execution_time',1500); /// le traitement peux être long ...
  495. try{
  496. /// Récupération du flux
  497. if($fromcache == 1 && file_exists($cachefile)){
  498. $mainFluxUrl = $cachefile;
  499. }else{
  500. $mainFluxUrl = $this->constructFluxUrl();
  501. }
  502. $mainFluxStream = $this->_getFlux($mainFluxUrl);
  503. if(!$mainFluxStream)
  504. throw new Exception("Flux $mainFluxUrl ne répond pas ");
  505. if($mainFluxUrl != $cachefile) /// Copier le fichier en local
  506. file_put_contents($cachefile,$mainFluxStream);
  507. ///construction du dom
  508. $dom = new DOMDocument();
  509. $dom->preserveWhiteSpace = false;
  510. $dom->loadXML($mainFluxStream);
  511. $xpath = new DOMXpath($dom);
  512. /// list des agences
  513. $agences = $xpath->query('//agence');
  514. $message .= $agences->length." agences found in the xml $mainFluxUrl\n";
  515. $tb_oidrando = array();///tableau des oids traités
  516. foreach ($agences as $agence) {
  517. $codeAgence = $xpath->query('infos/code',$agence)->item(0)->nodeValue;
  518. $nomAgence = $xpath->query('infos/libelle',$agence)->item(0)->nodeValue;
  519. $dateAgence = $xpath->query('infos/date',$agence)->item(0)->nodeValue;
  520. $oidAgence = $this->_getAgenceOid($codeAgence,$nomAgence,$dateAgence);
  521. if(!$oidAgence){ /// si l'agence n'est pas publié on n'import rien
  522. $nbcircuit = $treks->length;
  523. $message .= "Agence $nomAgence ($codeAgence) non trouvé dans vagabondages ($nbcircuit circuits)\n";
  524. continue;
  525. }
  526. /// parcours des treks de l'agence
  527. $tb_oidrando[$oidAgence] = array();
  528. $treks = $xpath->query('treks/trek',$agence);
  529. $message .= '- '.$nomAgence.' : '.$treks->length.' treks trouvé '."\n";
  530. foreach ($treks as $trek){
  531. $rando = array();
  532. $rando['agences_oid'] = $oidAgence;
  533. $rando['trek_id'] = $trek->attributes->getNamedItem("id")->nodeValue;
  534. $disp_rando = $this->_getRando($rando['trek_id']);
  535. ///si la mise à jour est interdite on ne fait rien
  536. if($disp_rando['onomaj']->raw == 1){
  537. $tb_oidrando[$oidAgence][] = $disp_rando['oid'];
  538. continue;
  539. }
  540. /// on vérifie que le pays est validé en console, si non on invalide la rando
  541. /// si le pays n'est pas remplit dans webresa le circuit ne sera pas remonté
  542. $oidPays = $this->_getPaysOid(strtolower($xpath->query('pays',$trek)->item(0)->nodeValue),$oidAgence);
  543. if(!$oidPays ){
  544. if($disp_rando['oid']) $this->_unpublishRando($disp_rando['oid']);
  545. continue;
  546. }
  547. ///si la rando n'existe pas on met le champ publié dans l'etat initial
  548. if(!$disp_rando['oid'])
  549. $rando['PUBLISH'] = $this->defaultispublished?1:2;
  550. $rando['pays'] = $oidPays;
  551. $rando['webresa_id'] = $xpath->query('uid',$trek)->item(0)->nodeValue;
  552. $rando['webresa_num'] = $xpath->query('numero',$trek)->item(0)->nodeValue;
  553. $rando['code'] = $xpath->query('code',$trek)->item(0)->nodeValue;
  554. $rando['href'] = $xpath->query('href',$trek)->item(0)->nodeValue;
  555. $rando['region'] = $xpath->query('region',$trek)->item(0)->nodeValue;
  556. $rando['mode'] = $this->_setMode($xpath->query('mode',$trek)->item(0)->nodeValue);
  557. $rando['libelle'] = $xpath->query('libelle',$trek)->item(0)->nodeValue;
  558. $rando['duree'] = $xpath->query('duree',$trek)->item(0)->nodeValue;
  559. $rando['duree_nuit'] = $xpath->query('duree_nuit',$trek)->item(0)->nodeValue;
  560. $rando['marche'] = $xpath->query('marche',$trek)->item(0)->nodeValue;
  561. $rando['type_oid'] = $this->_setAttribut($xpath->query('type',$trek)->item(0)->nodeValue,'type_oid',$oidAgence);
  562. $rando['niveau_oid'] = $this->_setAttribut($xpath->query('niveau',$trek)->item(0)->nodeValue,'niveau_oid',$oidAgence);
  563. $rando['niveau_tech_oid'] = $this->_setAttribut($xpath->query('niveau_tech',$trek)->item(0)->nodeValue,'niveau_tech_oid',$oidAgence);
  564. $hebergements = $xpath->query('hebergements/hebergement',$trek);
  565. $rando['hebergements'] = array();
  566. foreach($hebergements as $hebergement){
  567. $rando['hebergements'][] = $this->_setAttribut($hebergement->nodeValue,'hebergements',$oidAgence);
  568. }
  569. $rando['hebergements'] = array_unique($rando['hebergements']);
  570. $themes = $xpath->query('themes/theme',$trek);
  571. $rando['themes'] = array();
  572. foreach($themes as $theme){
  573. $rando['themes'][] = $this->_setAttribut($theme->nodeValue,'themes',$oidAgence);
  574. }
  575. $rando['themes'] = array_unique($rando['themes']);
  576. $rando['activite'] = $this->_setAttribut($xpath->query('activite',$trek)->item(0)->nodeValue,'activite',$oidAgence);
  577. $rando['portage'] = $this->_setAttribut($xpath->query('portage',$trek)->item(0)->nodeValue,'portage',$oidAgence);
  578. $rando['nb_jour_portage'] = $xpath->query('nb_jour_portage',$trek)->item(0)->nodeValue;
  579. $rando['circuit_exception'] = ($xpath->query('circuit_exception',$trek)->item(0)->nodeValue == 1 || $xpath->query('circuit_exception',$trek)->item(0)->nodeValue == 'oui' )?1:2;
  580. $rando['ville_depart'] = $xpath->query('ville_depart',$trek)->item(0)->nodeValue;
  581. $rando['ville_arrivee'] = $xpath->query('ville_arrivee',$trek)->item(0)->nodeValue;
  582. $rando['geoloc_depart'] = $this->degree2dec($xpath->query('latitude_depart',$trek)->item(0)->nodeValue).";".$this->degree2dec($xpath->query('longitude_depart',$trek)->item(0)->nodeValue);
  583. $rando['geoloc_arrivee'] = $this->degree2dec($xpath->query('latitude_arrivee',$trek)->item(0)->nodeValue).";".$this->degree2dec($xpath->query('longitude_arrivee',$trek)->item(0)->nodeValue);
  584. $rando['prix_minimum'] = $xpath->query('prix_minimum',$trek)->item(0)->nodeValue;
  585. $rando['prix_maximum'] = $xpath->query('prix_maximum',$trek)->item(0)->nodeValue;
  586. $rando['tel'] = $xpath->query('tel',$trek)->item(0)->nodeValue;
  587. $rando['commentaire'] = $xpath->query('commentaire',$trek)->item(0)->nodeValue;
  588. $rando['fiche_technique'] = $xpath->query('fiche_technique',$trek)->item(0)->nodeValue;
  589. ///insertion ou Mise a jour
  590. $resinsert = $this->_insertUpdateRando($rando);
  591. if(!$resinsert['oid']){
  592. $message .= "\t".$rando['trek_id'].' erreur d\'insertion'.$resinsert;
  593. continue;
  594. }else{
  595. $tb_oidrando[$oidAgence][] = $resinsert['oid'];
  596. }
  597. ///traitement des images
  598. $insertedmedia = array();
  599. $images = $xpath->query('images/image',$trek);
  600. $ordrei = 1;
  601. foreach($images as $image){
  602. $insertedmedia[] = $this->_addMediaRando($resinsert['oid'], $image->nodeValue, 'image', $ordrei);
  603. }
  604. ///traitement des pdf
  605. $pdfs = $xpath->query('pdfs/pdf',$trek);
  606. $ordrep = 1;
  607. foreach($pdfs as $pdf){
  608. $insertedmedia[] = $this->_addMediaRando($resinsert['oid'], $pdf->nodeValue, 'pdf', $ordrep);
  609. }
  610. $this->_unpublishSsmod($resinsert['oid'], $insertedmedia ,1);
  611. ///traitement des dates de departs
  612. $departs = $xpath->query('departs/depart',$trek);
  613. $oidsdate = $this->_updateDeparts($resinsert['oid'],$departs,$xpath);
  614. $this->_unpublishSsmod($resinsert['oid'],$oidsdate,3);
  615. ///traitement fiche technique
  616. if(!empty($rando['fiche_technique'])){
  617. $fichetech = new DOMDocument();
  618. $fichetech->preserveWhiteSpace = false;
  619. $fichetech->load($rando['fiche_technique']);
  620. $xpathft = new DOMXpath($fichetech);
  621. $randocpl = array();
  622. $randocpl['trek_id'] = $rando['trek_id'];
  623. $randocpl['auteur'] = $xpathft->query('/fiche/header/auteur')->item(0)->nodeValue;
  624. $randocpl['datePublication'] = $this->sqlDate( $xpathft->query('/fiche/header/datePublication')->item(0)->nodeValue,"%d/%m/%Y" );
  625. $randocpl['dateLastModification'] = $this->sqlDate( $xpathft->query('/fiche/header/dateLastModification')->item(0)->nodeValue,"%d/%m/%Y" );
  626. $randocpl['urlIframeDate'] = $xpathft->query('/fiche/header/urlIframeDates')->item(0)->nodeValue;
  627. $randocpl['url2IframeDate'] = $xpathft->query('/fiche/header/url2IframeDates')->item(0)->nodeValue;
  628. $randocpl['resume'] = $xpathft->query('/fiche/contenu/resume')->item(0)->nodeValue;
  629. $randocpl['complement'] = $xpathft->query("//chapitre[nomChapitre='PROGRAMME']/complementProgramme")->item(0)->nodeValue;
  630. $randocpl['libelle1'] = $xpathft->query('/fiche/contenu/sousTitre')->item(0)->nodeValue;
  631. $jours = $xpathft->query("//chapitre[nomChapitre='PROGRAMME']/jours/jour");
  632. $cntjour = 1;
  633. $idprogramme = array();
  634. foreach($jours as $jour){
  635. $prog = array();
  636. $prog['PUBLISH'] = 1;
  637. $prog['treks_id'] = $resinsert['oid'];
  638. $prog['ordre'] = $cntjour++;
  639. $prog['nom_jour'] = $xpathft->query("nomJour",$jour)->item(0)->nodeValue;
  640. $prog['description'] = $this->tidyRepair($xpathft->query("contenuJour",$jour)->item(0)->nodeValue);
  641. $idprogramme[] = $prog['webresa_id'] = $jour->attributes->getNamedItem("ID")->nodeValue;;
  642. $this->_insertUpdateProgramme($prog);
  643. }
  644. $rubriques = $xpathft->query("//chapitre[nomChapitre='FICHE PRATIQUE']/rubriques/rubrique");
  645. $cnt = 1;
  646. $idFiches = array();
  647. foreach($rubriques as $rubrique){
  648. $prog = array();
  649. $prog['PUBLISH'] = 1;
  650. $prog['treks_id'] = $resinsert['oid'];
  651. $prog['ordre'] = $cnt++;
  652. $prog['libelle'] = $xpathft->query("nomRubrique",$rubrique)->item(0)->nodeValue;
  653. $prog['description'] = $this->tidyRepair($xpathft->query("contenuRubrique",$rubrique)->item(0)->nodeValue);
  654. $idFiches[] = $prog['webresa_id'] = $rubrique->attributes->getNamedItem("ID")->nodeValue;;
  655. $this->_insertUpdateRubrique($prog,5);
  656. }
  657. $rubriques = $xpathft->query("//chapitreLibre");
  658. $cnt = 1;
  659. $idFiches = array();
  660. foreach($rubriques as $rubrique){
  661. $prog = array();
  662. $prog['PUBLISH'] = 1;
  663. $prog['treks_id'] = $resinsert['oid'];
  664. $prog['ordre'] = $cnt++;
  665. $prog['libelle'] = $xpathft->query("nomChapitreLibre",$rubrique)->item(0)->nodeValue;
  666. $prog['description'] = $this->tidyRepair($xpathft->query("contenuChapitreLibre",$rubrique)->item(0)->nodeValue);
  667. $idFiches[] = $prog['webresa_id'] = $rubrique->attributes->getNamedItem("ID")->nodeValue;;
  668. $this->_insertUpdateRubrique($prog,6);
  669. }
  670. $this->_cleanRubriques($resinsert['oid'],$idFiches);
  671. $resinsert = $this->_insertUpdateRando($randocpl);
  672. }
  673. unset($rando);
  674. if($param->get('getOne'))
  675. die($message);
  676. }
  677. }
  678. XLogs::notice('Webresa synchro',$message);
  679. return $message;
  680. }catch(Exception $e){
  681. XLogs::critical('Webresa synchro',$message);
  682. return 'Erreur found:'.$message.$e->getMessage();
  683. }
  684. }
  685. /**
  686. Appel manuel de la fonction d'import
  687. \return message de log a l'ecran
  688. */
  689. function importFluxManual($ar=NULL) {
  690. die(nl2br($this->importFlux($ar)));
  691. }
  692. /**
  693. Appel planifié de la fonction d'import
  694. \return message dans la cron
  695. */
  696. function importFluxCron(XModScheduler &$s, $o, $arraymore) {
  697. $mess = $this->importFlux($ar);
  698. $s->setStatusJob($o->KOID, 'finished', $mess);
  699. }
  700. /**
  701. Appel manuel de la fonction d'import
  702. \return message de log a l'ecran
  703. */
  704. function getTrekFromCache($ar=NULL) {
  705. $param = new XParam($ar,array());
  706. $cachefile = $this->cachefile;
  707. $id = $param->get('trek_id');
  708. ini_set('max_execution_time',1500); /// le traitement peux être long ...
  709. try{
  710. /// Récupération du flux
  711. $mainFluxUrl = $cachefile;
  712. $mainFluxStream = $this->_getFlux($mainFluxUrl);
  713. if(!$mainFluxStream)
  714. throw new Exception("Flux $mainFluxUrl ne répond pas ");
  715. ///construction du dom
  716. $dom = new DOMDocument();
  717. $dom->preserveWhiteSpace = false;
  718. $dom->loadXML($mainFluxStream);
  719. $xpath = new DOMXpath($dom);
  720. $treks = $xpath->query("//trek[@id='$id']");
  721. foreach($treks as $trek){
  722. header ("Content-Type:text/xml");
  723. die($trek->C14N());
  724. }
  725. }catch(Exception $e){
  726. die('Erreur found:'.$message.$e->message);
  727. }
  728. }
  729. /**
  730. * Groupe de Functions utilisés par la gestion du module
  731. * - Mise à jour
  732. * - supression
  733. *
  734. */
  735. public function updateSchema($ar){
  736. $mess = XModWebresaWd::updateSchema($this->prefix);
  737. $mess .= XModWebresaWd::updateProperties($this);
  738. $mess .= XModWebresaWd::addTemplates($this);
  739. XDBIni::setStatic($this->_moid.'version',XModWebresaWd::version);
  740. XShell::toScreen2('','message',$mess);
  741. }
  742. /**
  743. * Liste des tables utilisées par le module
  744. */
  745. public function usedTables() {
  746. $schematable = XModWebresaWd::getSchemaTables();
  747. $tables = array();
  748. foreach($schematable as $key => $tabledef){
  749. if ($key>0 && $tabledef[0])
  750. $tables[] = $this->prefix.$tabledef[0];
  751. }
  752. return $tables;
  753. }
  754. /**
  755. * Liste des tables principales du module
  756. */
  757. public function usedMainTables() {
  758. return array($this->table);
  759. }
  760. /**
  761. * Suppression du module et modules associés
  762. */
  763. function delete($ar) {
  764. //Module associé
  765. $modules = array($this->moidagences,$this->moidattributs,$this->moidpays,$this->ssmod1,$this->ssmod2,$this->ssmod3,$this->ssmod4,$this->ssmod4,$this->ssmod4);
  766. foreach($modules as $km=>$moid){
  767. if($moid && XModule::moduleExists($moid) ){
  768. $mod = XModule::objectFactory($moid);
  769. $ar1['withtable'] = false;
  770. $message .= $mod->delete($ar1)."\n";
  771. XModule::clearCache();
  772. }
  773. }
  774. $message .= parent::delete($ar);
  775. return XShell::toScreen2($tplentry,'message',$message);
  776. }
  777. /**
  778. * Page d'information du module
  779. */
  780. function getInfos($ar=NULL){
  781. $p=new XParam($ar,array('tplentry'=>TZR_RETURN_DATA));
  782. $tplentry=$p->get('tplentry');
  783. $ar['tplentry']=TZR_RETURN_DATA;
  784. $ret=parent::getInfos($ar);
  785. unset($ret['infos']['size']);
  786. $ret['infos']['version']->label = 'Version du schema';
  787. $currentversion = XDBIni::getStatic($this->_moid.'version','val');
  788. $ret['infos']['version']->html = $currentversion;
  789. $ret['infos']['lastfluxurl']->label = 'Url du dernier fluw analysé';
  790. $ret['infos']['lastfluxurl']->html = XDBIni::getStatic($this->_moid.'lastfluxurl','val');
  791. $ret['infos']['lastfluxdate']->label = 'Date de la dernière analyse';
  792. $ret['infos']['lastfluxdate']->html = XDBIni::getStatic($this->_moid.'lastfluxdate','val');
  793. $ret['infos']['lastfluxheader']->label = 'header de la réponse lors de la dernière analyse';
  794. $ret['infos']['lastfluxheader']->html = nl2br(XDBIni::getStatic($this->_moid.'lastfluxheader','val'));
  795. return XShell::toScreen1($tplentry,$ret);
  796. }
  797. function degree2dec($str){
  798. if(!$str) return false;
  799. $tmp = preg_split("/[°'\"]{1,2}/",$str,NULL,PREG_SPLIT_NO_EMPTY);
  800. $deg = (integer)$tmp[0];
  801. $min = (integer)$tmp[1];
  802. $sec = (integer)$tmp[2];
  803. $res = $deg + ((($sec/60)+$min)/60);
  804. return $res;
  805. }
  806. function alphatosqldate($str){
  807. $tb = explode('.',$str);
  808. return $tb[2].'-'.$tb[1].'-'.$tb[0];
  809. }
  810. function sqlDate($str,$fmt="%d/%m/%Y %H:%M:%S"){
  811. if(empty($str)) return '';
  812. $ar = strptime($str,$fmt);
  813. return date('Y-m-d',mktime(12,0,0,$ar['tm_mon']+1,$ar['tm_mday'],1900+$ar['tm_year']));
  814. }
  815. //retourn le nombre de jour entre 2 date
  816. function diffDate($d1,$d2){
  817. $ar1 = strptime($d2,"%Y-%m-%d");
  818. $ar2 = strptime($d1,"%Y-%m-%d");
  819. $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']);
  820. return round($diffs/60/60/24);
  821. }
  822. /**
  823. * Creation automatique de la tâche
  824. *
  825. */
  826. public function chk($ar=NULL) {
  827. $this->_createTask($ar);
  828. return parent::chk($ar);
  829. }
  830. protected function _createTask($ar){
  831. $cnt = countSelectQuery("select count(*) from TASKS where amoid='".$this->_moid."' and status='cron' ");
  832. if(!$cnt) {
  833. $pc=array();
  834. $pc['title'] = $this->modulename.' - Import Flux';
  835. $pc['ptime'] = 'today';
  836. $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>';
  837. $pc['status'] = 'cron';
  838. $pc['amoid'] = $this->_moid;
  839. $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>';
  840. $pc['tplentry'] = TZR_RETURN_DATA;
  841. $xs = XDataSource::objectFactoryHelper8('BCLASS=XDSTable&SPECS=TASKS');
  842. $r1 = $xs->procInput($pc);
  843. $m = XLabels::getSysLabel('xmodwebresa','task_missing');
  844. XShell::toScreen2('','message',$m);
  845. }
  846. }
  847. }
  848. ?>