Subversion Repositories eFlore/Applications.cel

Rev

Rev 3232 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
1425 aurelien 1
<?php
2462 jpm 2
// declare(encoding='UTF-8');
1425 aurelien 3
/**
2462 jpm 4
 * Classe recherchant des infos sur un taxon.
1926 raphael 5
 *
2462 jpm 6
 * Elle appelle les web service d'eflore pour éviter que le code client ne soit dépendant de la BDD d'eFlore.
2152 jpm 7
 *
2462 jpm 8
 * @internal   Mininum PHP version : 5.2
9
 * @category   CEL
10
 * @package    Services
11
 * @subpackage Bibliothèques
12
 * @version    0.1
13
 * @author     Mathias CHOUET <mathias@tela-botanica.org>
14
 * @author     Jean-Pascal MILCENT <jpm@tela-botanica.org>
15
 * @author     Aurelien PERONNET <aurelien@tela-botanica.org>
16
 * @license    GPL v3 <http://www.gnu.org/licenses/gpl.txt>
17
 * @license    CECILL v2 <http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt>
18
 * @copyright  1999-2014 Tela Botanica <accueil@tela-botanica.org>
1425 aurelien 19
 */
20
class RechercheInfosTaxonBeta extends Cel {
1926 raphael 21
 
22
	const DEBUG = FALSE;
23
 
1427 aurelien 24
	private $url_service_nom = null;
25
	private $url_service_taxon = null;
26
	private $url_service_chorologie = null;
2152 jpm 27
 
1487 aurelien 28
	private $masque_recherche = null;
1527 aurelien 29
	private $code_referentiel = 'bdtfx';
1784 raphael 30
 
31
	// initialisé à TRUE par rechercherInfosSurTexteCodeOuNumTax()
32
	// si l'espèce passée a le motif <ref>:(nt|nn):<num>, eg: isfan:nt:1591
33
	public $is_notation_spe = FALSE;
34
 
2462 jpm 35
	// un cache utilisé pour les requêtes effectuées sur /service:eflore:0.1/bdtfx/noms?masque=
36
	// qui sont lourdes, et parfois identiques (cf cas de l'import XLS)
37
	static $cache = array();
1928 raphael 38
 
3473 killian 39
	public function __construct($config, $code_referentiel = 'bdtfx') {
1527 aurelien 40
		parent::__construct($config);
2462 jpm 41
		$this->setReferentiel($code_referentiel);
42
	}
1927 raphael 43
 
2462 jpm 44
	public function setReferentiel($code_referentiel = 'bdtfx') {
3227 delphine 45
		$sousref = array("apdfna" => array("apd", "fna"),
46
				"apdfta" => array("apd", "fta"),
47
				"apdfsa" => array("apd", "fsa"),
48
				"taxref", "vascan");
49
		if (array_key_exists($code_referentiel, $sousref)) {
50
			$this->code_referentiel = $sousref[$code_referentiel][0];
51
			$this->formaterUrlsServicesSousRef($this->config, $sousref[$code_referentiel][1]);
52
		} else {
53
			$this->code_referentiel = $code_referentiel;
54
			$this->formaterUrlsServices($this->config);
55
		}
1527 aurelien 56
	}
2152 jpm 57
 
1527 aurelien 58
	private function formaterUrlsServices($config) {
59
		$this->url_service_nom = str_replace('{referentiel}', $this->code_referentiel ,$config['eflore']['url_service_nom']);
60
		$this->url_service_taxon = str_replace('{referentiel}', $this->code_referentiel ,$config['eflore']['url_service_taxon']);
3227 delphine 61
		$this->url_service_nom_m = str_replace('{referentiel}', $this->code_referentiel ,$config['eflore']['url_service_nom'])."?";
62
		$this->url_service_taxon_m = str_replace('{referentiel}', $this->code_referentiel ,$config['eflore']['url_service_taxon'])."?";
1427 aurelien 63
		$this->url_service_chorologie_obs = $config['eflore']['url_service_chorologie_obs'];
1852 raphael 64
		$this->config = $config;
1425 aurelien 65
	}
3227 delphine 66
 
67
	private function formaterUrlsServicesSousRef($config, $sousref) {
68
		$this->url_service_nom = str_replace('{referentiel}', $this->code_referentiel ,$config['eflore']['url_service_nom']);
69
		$this->url_service_taxon = str_replace('{referentiel}', $this->code_referentiel ,$config['eflore']['url_service_taxon']);
70
		$this->url_service_nom_m = str_replace('{referentiel}', $this->code_referentiel ,$config['eflore']['url_service_nom'])."?masque.ref=".$sousref."&";
71
		$this->url_service_taxon_m = str_replace('{referentiel}', $this->code_referentiel ,$config['eflore']['url_service_taxon'])."?masque.ref=".$sousref."&";
72
		$this->url_service_chorologie_obs = $config['eflore']['url_service_chorologie_obs'];
73
		$this->config = $config;
74
	}
2152 jpm 75
 
1425 aurelien 76
	public function rechercherGenreEspeceSurPrefixe($genre = null, $espece = null) {
2152 jpm 77
		$liste_genre_espece = array();
1487 aurelien 78
		$this->masque_recherche = trim(trim($genre).' '.trim($espece,' *'));
79
		$masque = urlencode($this->masque_recherche);
3227 delphine 80
		if(self::DEBUG) error_log("CEL fetch: " . $this->url_service_nom_m.'masque='.$masque.'&recherche=etendue&retour.format=min&navigation.limite=50&ns.structure=au');
81
		$urlService = $this->url_service_nom_m.'masque='.$masque.'&recherche=etendue&retour.format=min&navigation.limite=50&ns.structure=au,an';
2123 mathias 82
		$requete = @file_get_contents($urlService);
1425 aurelien 83
		if($requete != '') {
2152 jpm 84
			$requete = json_decode($requete);
1425 aurelien 85
			if(is_object($requete) && isset($requete->resultat)) {
86
				foreach ($requete->resultat as $id => $res) {
1427 aurelien 87
					$retenu = ($res->retenu == "true") ? '3' : '4';
2243 mathias 88
					$liste_genre_espece[] = array($res->nom_sci_complet, $id, $retenu, $res->nom_sci);
1425 aurelien 89
				}
90
			}
2152 jpm 91
			usort($liste_genre_espece, array($this, 'comparerParRetenuPuisNom'));
1425 aurelien 92
		}
93
		return $liste_genre_espece;
94
	}
2152 jpm 95
 
1427 aurelien 96
	function comparerParRetenuPuisNom($a, $b) {
97
		if($a[2] == 3 && $b[2] != 3) {
98
			return -1;
99
		} elseif($a[2] != 3 && $b[2] == 3) {
100
			return 1;
101
		} else {
2243 mathias 102
			// maintient l'ordre lexicographique - et normalement le genre en premier, en utilisant le nom_sci (sans auteur)
103
			return strcasecmp($a[3], $b[3]);
104
			// @WTF levenshtein c'était juste pour garder le genre en premier ?
105
			//return levenshtein($this->masque_recherche, $a[0]) >= levenshtein($this->masque_recherche, $b[0]);
1427 aurelien 106
		}
1425 aurelien 107
	}
2152 jpm 108
 
1425 aurelien 109
	public function effectuerRequeteInfosComplementairesEtFormaterNom($numNom) {
110
		$resultat_infos_complementaires = (array)$this->effectuerRequeteInfosComplementairesSurNumNom($numNom);
111
		$retour_infos_complementaires = array();
1780 raphael 112
		if (isset($resultat_infos_complementaires['nom_retenu_complet']) && $resultat_infos_complementaires['nom_retenu_complet']) {
1926 raphael 113
			$retour_infos_complementaires=array((self::supprimerBiblio($resultat_infos_complementaires['nom_retenu_complet'])));
114
		}
2152 jpm 115
 
1425 aurelien 116
		return $retour_infos_complementaires;
117
	}
2152 jpm 118
 
1425 aurelien 119
	public function rechercherInformationsComplementairesSurNom($nom_saisi) {
1487 aurelien 120
		$nom_saisi = trim($nom_saisi);
1486 aurelien 121
		// Essai de recherche sur le nom saisi tel quel
1862 raphael 122
		$liste_genre_espece = $this->effectuerRequeteUrlRecherche($nom_saisi, 'stricte');
123
		if($liste_genre_espece) return $liste_genre_espece;
124
 
125
		// Essai de recherche stricte en tentant de supprimer le nom d'auteur
126
		if( ($nom_saisi_sans_auteur = self::supprimerAuteur($nom_saisi)) ) { // ne pas faire la requête sur un mot vide
127
			$liste_genre_espece = $this->effectuerRequeteUrlRecherche($nom_saisi_sans_auteur, 'stricte');
1486 aurelien 128
		}
1862 raphael 129
		if($liste_genre_espece) return $liste_genre_espece;
130
 
131
		// avant-dernière tentative : essai de recherche étendue
132
		$liste_genre_espece = $this->effectuerRequeteUrlRecherche($nom_saisi, 'etendue');
133
		if($liste_genre_espece) return $liste_genre_espece;
134
 
135
		// dernière tentative: concaténation (nom_sci,auteur) (= nom-retenu généré utilisé comme nom_sci)
136
		$liste_genre_espece = $this->effectuerRequeteUrlRecherche($nom_saisi, 'concat');
2152 jpm 137
 
1486 aurelien 138
		return $liste_genre_espece;
139
	}
2152 jpm 140
 
1862 raphael 141
	private function effectuerRequeteUrlRecherche($nom_saisi, $mode = 'stricte') {
2462 jpm 142
		$url = sprintf(
143
			'%1$s?masque=%2$s&recherche=%3$s&ns.format=txt&retour.champs=%4$s&navigation.limite=1',
144
			$this->url_service_nom,
145
			urlencode($nom_saisi),
146
			$mode,
147
			implode(',', array("id","nom_sci","auteur","nom_retenu.id","famille","num_taxonomique","nom_retenu_complet")));
1928 raphael 148
 
149
		if(! array_key_exists($url, self::$cache)) {
2462 jpm 150
			if(self::DEBUG) error_log("CEL fetch: " . $url);
151
			$res = @json_decode(file_get_contents($url));
152
			self::$cache[$url] = $res;
153
		} else {
154
			$res = self::$cache[$url];
155
		}
1780 raphael 156
		if(!$res) return NULL;
157
		$resultat = (array)$res->resultat;
158
		return array_pop($resultat);
1486 aurelien 159
	}
2152 jpm 160
 
1833 raphael 161
	static function supprimerAuteur($nom_saisi) {
1486 aurelien 162
		// TODO: gérer les hybrides
1833 raphael 163
		if(self::estUnHybride($nom_saisi) || self::estUneFormuleHybridite($nom_saisi)) {
1486 aurelien 164
			$nom_decoupe = explode(' ', $nom_saisi);
1930 raphael 165
			$derniere_position_hybride = array_keys($nom_decoupe, 'x');
166
			$nom_saisi_sans_auteur = implode(' ',array_slice($nom_decoupe, 0, end($derniere_position_hybride) + 2));
1486 aurelien 167
		} else {
1833 raphael 168
			/* Attention le parseur de nom n'est pas fiable à 100%
2152 jpm 169
			   mais ça marche dans la plupart des cas
1833 raphael 170
			   à part les formules d'hybridité saisies avec un auteur */
171
			$nameparser = new NameParser();
1486 aurelien 172
			$auteur = $nameparser->parse_auth($nom_saisi);
173
			$nom_saisi_sans_auteur = str_replace($auteur, '', $nom_saisi);
174
		}
175
 
1833 raphael 176
		return trim($nom_saisi_sans_auteur);
1486 aurelien 177
	}
2152 jpm 178
 
1833 raphael 179
	static function estUneFormuleHybridite($nom_saisi) {
1486 aurelien 180
		return strpos($nom_saisi,' x ') !== false;
181
	}
2152 jpm 182
 
1833 raphael 183
	static function estUnHybride($nom_saisi) {
1486 aurelien 184
		return strpos($nom_saisi,'x ') === 0;
185
	}
2152 jpm 186
 
1852 raphael 187
	public function effectuerRequeteInfosComplementairesSurNumNom($num_nom, $ref = NULL) {
188
		if($ref && isset($this->config['eflore']['api_host'])) {
1926 raphael 189
			if(self::DEBUG) error_log("CEL fetch: " .$this->config['eflore']['api_host'] . '/');
1852 raphael 190
			return @json_decode(file_get_contents($this->config['eflore']['api_host'] . '/' .
3232 killian 191
			$this->code_referentiel . '/' .
1926 raphael 192
			'noms' . '/' .
193
			$num_nom .
194
			'?retour.champs=' . implode(',', array('nom_sci,auteur',
195
			'id',
196
			'nom_retenu_complet',
197
			'nom_retenu.id',
198
			'num_taxonomique',
199
			'famille'))));
1852 raphael 200
		}
201
		// XXX: compat
1926 raphael 202
		if(self::DEBUG) error_log("CEL fetch: " . $this->url_service_nom.'/'.$num_nom.'?retour.champs=nom_sci,auteur,id,nom_retenu_complet,nom_retenu.id,num_taxonomique,famille');
1780 raphael 203
		return @json_decode(file_get_contents($this->url_service_nom.'/'.$num_nom.'?retour.champs=nom_sci,auteur,id,nom_retenu_complet,nom_retenu.id,num_taxonomique,famille'));
1425 aurelien 204
	}
1780 raphael 205
 
206
	static function supprimerBiblio($nom) {
1805 raphael 207
		return trim(preg_replace('/ \[.*\]/','',$nom));
1425 aurelien 208
	}
2152 jpm 209
 
1425 aurelien 210
	public function rechercherNumTaxSurNumNom($num_nom) {
211
		$nt = null;
1427 aurelien 212
		$url = $this->url_service_nom."/".$num_nom.'?retour.champs=num_taxonomique';
1926 raphael 213
		if(self::DEBUG) error_log("CEL fetch: $url");
1425 aurelien 214
		$resultat = @file_get_contents($url);
215
		if($resultat != '') {
216
			$infos = json_decode($resultat);
217
			$nt = $infos->num_taxonomique;
218
		}
2152 jpm 219
 
1425 aurelien 220
		return $nt;
221
	}
2152 jpm 222
 
1425 aurelien 223
	public function taxonEstPresentDansDepartement($num_taxon,$code_departement) {
224
		$presence_taxon = false;
1427 aurelien 225
		$url = $this->url_service_chorologie_obs.'?masque.departement='.$code_departement.'&masque.determination.nt='.$num_taxon.'&navigation.limite=1';
1926 raphael 226
		if(self::DEBUG) error_log("CEL fetch: $url");
1425 aurelien 227
		$resultat = @file_get_contents($url);
228
		if($resultat != '') {
229
			$resultat = json_decode($resultat);
230
			if(is_object($resultat) && isset($resultat->resultat) && count($resultat->resultat) > 0) {
231
				$presence_taxon = true;
232
			}
233
		}
234
		return $presence_taxon;
235
	}
2152 jpm 236
 
237
	/* texte libre, nom scientifique,
238
	   ou code nomenclatural (format bdtfx:nn:999999)
1784 raphael 239
	   ou code taxonomique (format bdtfx:nt:999999)
1780 raphael 240
	   TODO: voir ce qu'on fait pour l'import de différent référentiels */
1425 aurelien 241
	function rechercherInfosSurTexteCodeOuNumTax($identifiant_espece) {
1784 raphael 242
		preg_match('/(' . implode('|', Cel::$referentiels_valides) .'):(nn|nt):(\d+)/i', $identifiant_espece, $elements);
243
		if($elements) {
244
			$this->is_notation_spe = TRUE;
245
			list(, $ref, $type, $num) = $elements;
1796 raphael 246
 
247
			if($ref != $this->code_referentiel) {
248
				// TODO: ignorer la colonne référentiel, et utiliser le référentiel donné
249
				// mais il faut alors avertir le service (d'import/modif) d'utiliser le référentiel
250
				// passé au nom d'espèce
1852 raphael 251
				// Seul le effectuerRequeteInfosComplementairesSurNumNom() le supporte, car c'est encore
252
				// un peu complexe à implémenter proprement pour cause d'attributs de classes.
1796 raphael 253
			}
1784 raphael 254
			// Numero nomenclatural
255
			if ($type == 'nn') {
1852 raphael 256
				$obj = $this->effectuerRequeteInfosComplementairesSurNumNom($num, $ref);
1784 raphael 257
			}
258
			// Numero taxonomique
259
			else {
260
				//TODO: retourner moins de champs grâce au paramètre retour.champs
1926 raphael 261
				if(self::DEBUG) error_log("CEL fetch: " . $this->url_service_taxon."/nt:".$num);
1784 raphael 262
				$obj = @json_decode(file_get_contents($this->url_service_taxon."/nt:".$num));
263
			}
1796 raphael 264
			if($obj) $obj->ref = $ref;
1784 raphael 265
			return $obj;
266
		}
1746 raphael 267
 
1780 raphael 268
		// Nom scientifique
269
		return $this->rechercherInformationsComplementairesSurNom($identifiant_espece);
1425 aurelien 270
	}
2152 jpm 271
 
1591 aurelien 272
	public function rechercherSynonymesSurNumNom($num_nom) {
273
		$retour = array();
1926 raphael 274
		if(self::DEBUG) error_log("CEL fetch: " . $this->url_service_nom.'/'.$num_nom.'/relations/synonymie/?retour.format=min');
1780 raphael 275
		$resultat = @file_get_contents($this->url_service_nom.'/'.$num_nom.'/relations/synonymie/?retour.format=min');
1591 aurelien 276
		if($resultat != '') {
277
			$resultat = json_decode($resultat);
278
			if(is_object($resultat) && isset($resultat->resultat) && count($resultat->resultat) > 0) {
279
				$retour = $resultat->resultat;
280
			}
281
		}
282
		return $retour;
283
	}
3232 killian 284
}