Subversion Repositories eFlore/Projets.eflore-projets

Rev

Rev 1022 | Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
1021 mathias 1
<?php
2
//declare(encoding='UTF-8');
3
/**
4
 * Exemple de lancement du script : :
5
 * /opt/lampp/bin/php cli.php bdtao -a chargerTous
6
 *
7
 * Base de données des Trachéophytes (trachéo...quoi ?? C'est le truc avec le stylo Bic ?)
8
 * d'Afrique de l'Ouest (et Centrale mais faut pas le dire)
9
 *
10
 * @category	php 5.2
11
 * @package		eFlore/Scripts
12
 * @author		Mathias CHOUET <mathias@tela-botanica.org>
13
 * @copyright	Copyright (c) 2014, Tela Botanica (accueil@tela-botanica.org)
14
 * @license		http://www.cecill.info/licences/Licence_CeCILL_V2-fr.txt Licence CECILL
15
 * @license		http://www.gnu.org/licenses/gpl.html Licence GNU-GPL
16
 */
17
class Bdtao extends EfloreScript {
18
 
19
	private $table = null;
20
	private $tableMeta = null;
21
	private $pasInsertion = 1000;
22
	private $departInsertion = 0;
23
 
24
	protected $parametres_autorises = array();
25
 
26
	// Entêtes du nouveau fichier Rtax à produire
27
	protected $entetesRtax = array("num_nom","num_nom_retenu","num_tax_sup","rang","nom_sci",
28
		"nom_supra_generique","genre","epithete_infra_generique","epithete_sp",
29
		"type_epithete","epithete_infra_sp","cultivar_groupe","cultivar","nom_commercial",
30
		"auteur","annee","biblio_origine","notes","nom_addendum","homonyme","num_type",
31
		"num_basionyme","synonyme_proparte","synonyme_douteux","synonyme_mal_applique",
32
		"synonyme_orthographique","orthographe_originelle","hybride_parent_01",
33
		"hybride_parent_01_notes","hybride_parent_02","hybride_parent_02_notes",
34
		"nom_francais","presence","statut_origine ","statut_introduction","statut_culture","exclure_taxref");
35
 
36
	public function initialiserProjet($projetNom) {
37
		parent::initialiserProjet($projetNom);
38
		$this->table = Config::get("bdtao");
39
		$this->tableMeta = Config::get("bdtaoMeta");
40
	}
41
 
42
	public function executer() {
43
		try {
44
			$this->initialiserProjet('bdtao');
45
 
46
			// Lancement de l'action demandée
47
			$cmd = $this->getParametre('a');
48
			switch ($cmd) {
49
				case 'tout' :
50
					$ok = $this->productionCsvPourReferentiels();
51
					if ($ok === true) {
52
						$this->integrationEFlore();
53
					}
54
					break;
55
				case 'ref' : // partie 1 : "referentiels"
56
					$this->productionCsvPourReferentiels();
57
					break;
58
				case 'eflore' : // partie 2 : "eFlore"
59
					$this->integrationEFlore();
60
					break;
61
				case 'nettoyage' :
62
					$this->nettoyage();
63
					break;
64
				case 'chargerStructureSql' :
65
					//$this->creerStructure();
66
					$this->chargerStructureSql();
67
					break;
68
				case 'verifierEtGenererCsvRtax' :
69
					$this->verifierEtGenererCsvRtax();
70
					break;
71
				case 'chargerCsvRtax' :
72
					$this->chargerCsvRtax();
73
					break;
74
				case 'changerRangs' :
75
					$this->changerRangs();
76
					break;
77
				case 'completerNumNomRetenu' :
78
					$this->completerNumNomRetenu();
79
					break;
80
				case 'supprimerNumTaxSupPourSynonymes' :
81
					$this->supprimerNumTaxSupPourSynonymes();
82
					break;
83
				case 'subspAutonymes' :
84
					$this->subspAutonymes();
85
					break;
86
				case 'genererNomSupraGenerique' :
87
					$this->genererNomSupraGenerique();
88
					break;
89
				case 'genererEpitheteInfraGenerique' :
90
					$this->genererEpitheteInfraGenerique();
91
					break;
92
				case 'exporterCSVModifie' :
93
					$this->exporterCSVModifie();
94
					break;
95
				case 'genererChpNumTax' :
96
					$this->genererChpNumTax();
97
					break;
98
				case 'genererNomSciHtml' :
99
					$this->genererChpNomSciHtml();
100
					break;
101
				case 'genererChpNomComplet' :
102
					$this->genererChpNomComplet();
103
					break;
104
				case 'genererChpFamille' :
105
					$this->genererChpFamille();
106
					break;
107
				case 'genererChpHierarchie' :
108
					$this->genererChpHierarchie();
109
					break;
110
				default :
111
					throw new Exception("Erreur : la commande '$cmd' n'existe pas!");
112
			}
113
		} catch (Exception $e) {
114
			$this->traiterErreur($e->getMessage());
115
		}
116
	}
117
 
118
	// Lance la première moitié du boulot, et s'arrête lorsque le fichier CSV
119
	// au format Rtax est rempli avec les données amendées - il est prêt à rentrer dans Rtxß.
120
	// Retourne true si tout s'est bien passé, false sinon
121
	protected function productionCsvPourReferentiels() {
122
		$retour = false;
123
		$this->nettoyage();
124
		$this->chargerStructureSql();
125
		$verifOk = $this->verifierEtGenererCsvRtax();
126
		if ($verifOk === true) {
127
			$chgtOk = $this->chargerCsvRtax();
128
			if ($chgtOk) {
129
				$this->changerRangs();
130
				$this->completerNumNomRetenu();
131
				$this->supprimerNumTaxSupPourSynonymes();
132
				$this->subspAutonymes();
133
				$this->genererNomSupraGenerique();
134
				$this->genererEpitheteInfraGenerique();
135
				$this->exporterCSVModifie();
136
				$retour = true;
137
			}
138
		}
139
		return $retour;
140
	}
141
 
142
	// Lance la seconde moitié du boulot, et s'arrête lorsque le référentiel
143
	// est inséré dans la base eFlore.
144
	// Retourne true si tout s'est bien passé, false sinon
145
	protected function integrationEFlore() {
146
		$retour = false;
147
		$this->genererChpNumTax();
148
		$this->genererChpNomSciHtml();
149
		$this->genererChpFamille();
150
		$this->genererChpNomComplet();
151
		$this->genererChpHierarchie();
152
		$retour = true;
153
		return $retour;
154
	}
155
 
156
	// -------------- partie Rtax -------------
157
 
158
	// Dézingue tout le bousin
159
	protected function nettoyage() {
160
		echo "---- suppression des tables\n";
161
		$req = "DROP TABLE IF EXISTS `" . $this->table . "`";
162
		$this->getBdd()->requeter($req);
163
		$req = "DROP TABLE IF EXISTS `" . $this->tableMeta . "`;";
164
		$this->getBdd()->requeter($req);
165
	}
166
 
167
	// Analyse le fichier CSV fourni par le CJBG, le vérifie et écrit un CSV minimal au format Rtax
168
	function verifierEtGenererCsvRtax() {
169
		$cheminCsvRtax = Config::get('chemins.csvRtax');
170
		$cheminCsvCjbg = Config::get('chemins.csvCjbg');
171
		$retour = false;
172
		echo "---- vérification CSV CJBG [$cheminCsvCjbg] et génération CSV Rtax\n";
173
 
174
		// Correspondances de colonnes pour le remplissage à minima du fichier CSV Rtax
175
		// Clefs: CJBG
176
		// Valeurs: Rtax
177
		$entetesCjbgVersRtax = array(
178
		    "id_name" => "num_nom",
179
		    "presence" => "presence",
180
		    "statut_introduction" => "statut_introduction",
181
		    "statut_origine" => "statut_origine",
182
		    "nom_addendum" => "nom_addendum",
183
		    "BASIONYME" => "num_basyonyme",
184
		    "NO_RANG" => "rang",
185
		    "auteur" => "auteur",
186
		    "ANNEE" => "annee",
187
		    "type_epithete" => "type_epithete",
188
		    "SYN_mal_applique" => "synonyme_mal_applique",
189
		    "nom_sci" => "nom_sci",
190
		    "num_tax_sup" => "num_tax_sup",
191
		    "num_nom_retenu" => "num_nom_retenu",
192
		    "genre" => "genre",
193
		    "NOTES" => "notes",
194
		    "epithete_sp" => "epithete_sp",
195
		    "epithete_infra_sp" => "epithete_infra_sp",
196
			// champs additionnels
197
		    "NOM_STANDARD2" => false,
198
		    "STATUT_SYN" => false, // @TODO convertir
199
		    "hybride_parents" => false, // toujours "x" => ??
200
		    "FAM APG3" => false,
201
		    "auth_genre" => false,
202
		    "auth_esp" => false
203
		);
204
 
205
		$analyseOK = true;
206
		$numLigne = 1;
207
		$idNames = array();
208
		// lecture CSV d'origine
209
		$csv = fopen($cheminCsvCjbg, "r");
210
		$donneesTransformees = array();
211
		if ($csv) {
212
			$entetes = fgetcsv($csv);
213
			//echo "Entetes: " . print_r($entetes, true) . "\n";
214
			while(($ligne = fgetcsv($csv)) !== false) {
215
				$numLigne++;
216
				$nouvelleLigne = array();
217
				if (isset($idNames[$ligne[0]])) {
218
					echo "Entrée dupliquée pour id_name [" . $ligne[0] . "]\n";
219
					$analyseOK = false;
220
				} else if (! is_numeric($ligne[0])) {
221
					echo "Ligne $numLigne : la clef [" . $ligne[0] . "] n'est pas un entier\n";
222
					$analyseOK = false;
223
				} else if ($ligne[0] == 0) {
224
					echo "Ligne $numLigne : la clef [" . $ligne[0] . "] vaut zéro\n";
225
					$analyseOK = false;
226
				} else {
227
					$idNames[$ligne[0]] = $ligne[13]; // stockage du nom retenu
228
					foreach ($ligne as $idx => $col) {
229
						$entete = $entetes[$idx];
230
						$ert = $entetesCjbgVersRtax[$entete];
231
						if (strpos($col, "\n") > -1) {
232
							echo "Info: la colonne $ert de la ligne $numLigne contient des retours chariot. Conversion en espaces.\n";
233
							$col = str_replace("\n", " ", $col);
234
						}
235
						$nouvelleLigne[$ert] = $col;
236
					}
237
					$donneesTransformees[] = $nouvelleLigne;
238
				}
239
			}
240
		} else {
241
			echo "Erreur lors de l'ouverture du fichier\n";
242
		}
243
 
244
		// Vérifications:
245
		// - existence des num_nom_retenu et num_tax_sup mentionnés
246
		// - réduction des chaînes de synonymie
247
		$nnrManquants = array();
248
		$ntsManquants = array();
249
		$chaineSyn = array();
250
		foreach ($donneesTransformees as $ligne) {
251
			$taxSup = $ligne['num_tax_sup'];
252
			$nomRet = $ligne['num_nom_retenu'];
253
			$numNom = $ligne['num_nom'];
254
			// Si un nom est retenu, son taxon supérieur doit être mentionné et exister
255
			if (($numNom == $nomRet) && $taxSup && (! isset($idNames[$taxSup])) && (! isset($ntsManquants[$taxSup]))) {
256
				$ntsManquants[$taxSup] = true;
257
			}
258
			// Si un nom retenu est mentionné, il doit exister et être un nom retenu
259
			if ($nomRet) {
260
				if (isset($idNames[$nomRet])) {
261
					/*$nrnr = $idNames[$nomRet];
262
					echo "Test pour nn $numNom, nr $nomRet, " . $nrnr . "\n";
263
					if ($nomRet && $nrnr != $nomRet) {
264
						if (! isset($chaineSyn[$nomRet])) {
265
							$chaineSyn[$nomRet] = true;
266
						}
267
					}*/
268
				} else {
269
					if (! isset($nnrManquants[$nomRet])) {
270
						$nnrManquants[$nomRet] = true;
271
					}
272
				}
273
			}
274
		}
275
		if (count($nnrManquants) > 0) {
276
			echo count($nnrManquants) . " Nom(s) retenu(s) absent(s):\n";
277
			echo "(" . implode(",", array_keys($nnrManquants)) . ")\n";
278
		}
279
		if (count($ntsManquants) > 0) {
280
			echo count($ntsManquants) . " Taxon(s) supérieur(s) absent(s):\n";
281
			echo "(" . implode(",", array_keys($ntsManquants)) . ")\n";
282
		}
283
		/*if (count($chaineSyn) > 0) {
284
			echo count($chaineSyn) . " Synonymes ne sont pas des noms retenus:\n";
285
			//echo "(" . implode(",", array_keys($chaineSyn)) . ")\n";
286
		}*/
287
 
288
		if ($analyseOK === true) {
289
			// Production CSV de destination
290
			$csvDestination = '';
291
			$csvDestination .= implode($this->entetesRtax, ',') . "\n";
292
			$tailleLigne = count($this->entetesRtax);
293
			foreach ($donneesTransformees as $dt) {
294
				//$ligne = array();
295
				$ligneCsv = '';
296
				$i = 0;
297
				foreach ($this->entetesRtax as $e) {
298
					/*if (isset($dt[$e])) {
299
						$ligne[] = $dt[$e];
300
					} else {
301
						$ligne[] = '';
302
					}*/
303
					if (isset($dt[$e]) && ($dt[$e] !== '')) {
304
						$ligneCsv .= '"' . $dt[$e] . '"';
305
					}
306
					if ($i < $tailleLigne) {
307
						$ligneCsv .= ',';
308
					}
309
					$i++;
310
				}
311
				$ligneCsv .= "\n";
312
				//$ligneCsv = '"' . implode($ligne, '","') . '"' . "\n"; // met des double guillemets sur les champs vides et /i
313
				$csvDestination .= $ligneCsv;
314
			}
315
			file_put_contents($cheminCsvRtax, $csvDestination);
316
			$retour = true;
317
		} else {
318
			echo "L'analyse a mis en évidence des erreurs. Interruption.\n";
319
		}
320
 
321
		return $retour;
322
	}
323
 
324
	// Charge le CSV minimal au format TexRaf
325
	protected function chargerCsvRtax() {
326
		$cheminCsvRtax = Config::get('chemins.csvRtax');
327
		echo "---- chargement du fichier CSV Rtax [$cheminCsvRtax]\n";
328
		$req = "LOAD DATA INFILE '" . $cheminCsvRtax . "' INTO TABLE " . $this->table
329
			. " FIELDS TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY '\n' IGNORE 1 LINES";
330
		$retour = $this->getBdd()->requeter($req);
331
		return $retour;
332
	}
333
 
334
	// Convertit les rangs du format chaispasquoi au format RexTaf
335
	protected function changerRangs() {
336
		echo "---- conversion des rangs\n";
337
		$rangs = array(
338
			"0" => "10",
339
			"1" => "20",
340
			"2" => "50",
341
			"3" => "53",
342
			"4" => "80",
343
			"5" => "140",
344
			"6" => "180",
345
			"7" => "190",
346
			"8" => "200",
347
			"9" => "220",
348
			"10" => "230",
349
			"11" => "240",
350
			"12" => "250",
351
			"13" => "260",
352
			"14" => "280",
353
			"15" => "290",
354
			"16" => "320",
355
			"17" => "340",
356
			"18" => "350",
357
			"19" => "360",
358
			"20" => "370",
359
			"26" => "440"
360
		);
361
		foreach ($rangs as $src => $dest) {
362
			echo "rang $src => rang $dest\n";
363
			$req = "UPDATE " . $this->table . " SET rang=$dest WHERE rang=$src;";
364
			$this->getBdd()->requeter($req);
365
		}
366
	}
367
 
368
	// Copie num_nom dans num_nom_retenu lorsque ce dernier est vide
369
	protected function completerNumNomRetenu() {
370
		echo "---- complétion des num_nom_retenu\n";
371
		$req = "UPDATE " . $this->table . " SET num_nom_retenu = num_nom WHERE num_nom_retenu='';";
372
		$this->getBdd()->requeter($req);
373
	}
374
 
375
	// Supprime le num_tax_sup pour les synonymes
376
	// et le met à 1 s'il est égal au num_nom
377
	protected function supprimerNumTaxSupPourSynonymes() {
378
		echo "---- suppression de num_tax_sup pour les synonymes et mise à 1 si égal à num_nom\n";
379
		$req = "UPDATE " . $this->table . " SET num_tax_sup = '' WHERE num_nom != num_nom_retenu;";
380
		$this->getBdd()->requeter($req);
381
		$req = "UPDATE " . $this->table . " SET num_tax_sup = 1 WHERE num_nom = num_tax_sup;";
382
		$this->getBdd()->requeter($req);
383
	}
384
 
385
	// Pour chaque subsp. autonyme, inscrit l'epithete_infra_sp
386
	protected function subspAutonymes() {
387
		echo "---- inscription de l'épithète infraspécifique des subsp. autonymes\n";
388
		$req = "SELECT num_nom, nom_sci, epithete_infra_sp FROM " . $this->table . " WHERE nom_sci LIKE '%subsp.%'";
389
		$res = $this->getBdd()->recupererTous($req);
390
 
391
		$nbres = count($res);
392
		$cpt = 0;
393
		$ok = 0;
394
		$ids = array();
395
		foreach ($res as $subsp) {
396
			$ns = $subsp['nom_sci'];
397
			$pos = strpos($ns, 'subsp.');
398
			$gsp = substr($ns, 0, $pos - 1);
399
			$sp = substr($gsp, strrpos($gsp, ' ') + 1);
400
			$sub = substr($ns, $pos + 8);
401
			if ($sub == $sp) {
402
				$cpt++;
403
				// @TODO
404
				// 1) récupérer l'auteur
405
				// 2) intégrer l'auteur avant "subsp." dans le nom_sci
406
				//echo "[$sp] || [$sub] || [" . $subsp['epithete_infra_sp'] . "]\n";
407
				if ($sub == $subsp['epithete_infra_sp']) {
408
					$ok++;
409
				} else {
410
					$reqMod = "UPDATE " . $this->table . " SET epithete_infra_sp='"
411
						. $sub . "' WHERE num_nom=" . $subsp['num_nom'];
412
					$this->getBdd()->requeter($reqMod);
413
				}
414
			}
415
		}
416
		echo "subsp.: $nbres\n";
417
		echo "Autonymes: $cpt dont $ok déjà inscrites\n";
418
	}
419
 
420
	// Copie le nom scientifique dans le nom supra générique pour les taxons de rang
421
	// supérieur au genre
422
	protected function genererNomSupraGenerique() {
423
		echo "---- complétion des noms supragénériques\n";
424
		$req = "UPDATE " . $this->table . " SET nom_supra_generique = nom_sci WHERE rang < 220";
425
		$res = $this->getBdd()->requeter($req);
426
	}
427
 
428
	// Copie le nom scientifique dans l'épithète infra générique pour les taxons de rang
429
	// entre genre et espèce
430
	protected function genererEpitheteInfraGenerique() {
431
		echo "---- complétion des épithètes infragénériques\n";
432
		$req = "UPDATE " . $this->table . " SET epithete_infra_generique = nom_sci WHERE rang > 220 AND rang < 290";
433
		$res = $this->getBdd()->requeter($req);
434
	}
435
 
436
	protected function exporterCSVModifie() {
437
		$cheminFichierCsvRtaxModifie = Config::get('chemins.csvRtaxModifie');
438
		echo "---- export du CSV Rtax modifié [$cheminFichierCsvRtaxModifie]\n";
439
		if (file_exists($cheminFichierCsvRtaxModifie)) {
440
			unlink($cheminFichierCsvRtaxModifie);
441
		}
442
		$req = "SELECT '" . implode("','", $this->entetesRtax) . "'"
443
			. " UNION ALL "
444
			. " SELECT * FROM " . $this->table . " INTO OUTFILE '" . $cheminFichierCsvRtaxModifie . "'"
445
			. " FIELDS TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY '\n'";
446
		$res = $this->getBdd()->requeter($req);
447
		// Remplacement des cases vides par '' aulieu de '""' (peut faire foirer l'import par la suite)
448
		exec("sed -i 's/\"\"//g' " . $cheminFichierCsvRtaxModifie);
449
	}
450
 
451
	// -------------- partie eFlore ------------- copiée depuis le script Bdtfx
452
 
453
	private function genererChpNomSciHtml() {
454
		echo "---- génération des noms scientifiques en HTML \n";
455
		$this->preparerTablePrChpNomSciHtml();
456
		$generateur = new GenerateurNomSciHtml();
457
		$nbreTotal = $this->recupererNbTotalTuples();
458
		$erreurs = array();
459
		$this->departInsertion = 0;
460
		while ($this->departInsertion < $nbreTotal) {
461
			$resultat = $this->recupererTuplesPrChpNomSciHtml();
462
 
463
			try {
464
				$nomsSciEnHtml = $generateur->generer($resultat);
465
			} catch (Exception $e) {
466
				$erreurs[] = $e->getMessage();
467
			}
468
 
469
			$this->remplirChpNomSciHtm($nomsSciEnHtml);
470
			$this->departInsertion += $this->pasInsertion;
471
			$this->afficherAvancement("Insertion des noms scientifique au format HTML dans la base par paquet de {$this->pasInsertion} en cours");
472
		}
473
		echo "\n";
474
 
475
		if (count($erreurs) > 0) {
476
			echo 'Erreurs lors de la génération HTML des noms scientifiques:\n' . print_r($erreurs, true) . "\n";
477
		}
478
	}
479
 
480
	private function preparerTablePrChpNomSciHtml() {
481
		echo "---- ajout de la colonne nom_sci_html \n";
482
		$requete = "SHOW COLUMNS FROM {$this->table} LIKE 'nom_sci_html' ";
483
		$resultat = $this->getBdd()->recuperer($requete);
484
		if ($resultat === false) {
485
			$requete = 	"ALTER TABLE {$this->table} ".
486
				'ADD nom_sci_html VARCHAR( 500 ) '.
487
				'CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ';
488
			$this->getBdd()->requeter($requete);
489
		}
490
	}
491
 
492
	private function recupererNbTotalTuples(){
493
		$requete = "SELECT count(*) AS nb FROM {$this->table} ";
494
		$resultat = $this->getBdd()->recuperer($requete);
495
		return $resultat['nb'];
496
	}
497
 
498
	private function recupererTuplesPrChpNomSciHtml() {
499
		$requete = 'SELECT 	num_nom, rang, nom_sci, nom_supra_generique, genre, epithete_infra_generique, '.
500
			'	epithete_sp, type_epithete, epithete_infra_sp,cultivar_groupe, '.
501
			'	nom_commercial, cultivar '.
502
			"FROM {$this->table} ".
503
			"LIMIT {$this->departInsertion},{$this->pasInsertion} ";
504
		$resultat = $this->getBdd()->recupererTous($requete);
505
		return $resultat;
506
	}
507
 
508
	private function remplirChpNomSciHtm($nomsSciHtm) {
509
		foreach ($nomsSciHtm as $id => $html) {
510
			$html = $this->getBdd()->proteger($html);
511
			$requete = "UPDATE {$this->table} SET nom_sci_html = $html WHERE num_nom = $id ";
512
			$resultat = $this->getBdd()->requeter($requete);
513
			if ($resultat === false) {
514
				throw new Exception("Erreur d'insertion pour le tuple $id");
515
			}
516
		}
517
	}
518
 
519
	// Attention c'est over-lent !
520
	private function genererChpNumTax() {
521
		$this->preparerTablePrChpNumTax();
522
		$erreurs = array();
523
		$this->departInsertion = 0;
524
		$dernier_num_tax = 0;
525
 
526
		$requete = 'SELECT num_nom '.
527
					'FROM '.$this->table.' '.
528
					'WHERE num_nom = num_nom_retenu AND num_nom_retenu != 0 '.
529
					'ORDER by num_nom_retenu ASC ';
530
 
531
		$resultat = $this->getBdd()->recupererTous($requete);
532
		foreach ($resultat as $taxon) {
533
			$dernier_num_tax++;
534
			$requete_maj = 'UPDATE '.$this->table.' '.
535
							'SET num_taxonomique = '.$dernier_num_tax.' '.
536
							'WHERE num_nom_retenu = '.$taxon['num_nom'];
537
			$this->getBdd()->requeter($requete_maj);
538
			$this->pasInsertion++;
539
			$this->afficherAvancement("Insertion des num tax, ".count($resultat)." num tax a traiter");
540
		}
541
		echo "\n";
542
		if (count($erreurs) > 0) {
543
			echo 'Erreurs lors de la génération des numéros taxonomiques' . print_r($erreurs, true) . "\n";
544
		}
545
	}
546
 
547
	private function preparerTablePrChpNumTax() {
548
		$requete = "SHOW COLUMNS FROM {$this->table} LIKE 'num_taxonomique' ";
549
		$resultat = $this->getBdd()->recuperer($requete);
550
		if ($resultat === false) {
551
			$requete = 	"ALTER TABLE {$this->table} ".
552
						'ADD num_taxonomique INT( 9 ) ';
553
			$this->getBdd()->requeter($requete);
554
		}
555
	}
556
 
557
	private function genererChpNomComplet() {
558
		$this->preparerTablePrChpNomComplet();
559
		$this->remplirChpNomComplet();
560
	}
561
 
562
	private function preparerTablePrChpNomComplet() {
563
		$requete = "SHOW COLUMNS FROM {$this->table} LIKE 'nom_complet' ";
564
		$resultat = $this->getBdd()->recuperer($requete);
565
		if ($resultat === false) {
566
			$requete = 	"ALTER TABLE {$this->table} ".
567
					'ADD nom_complet VARCHAR( 500 ) '.
568
					'CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ';
569
			$this->getBdd()->requeter($requete);
570
		}
571
	}
572
 
573
	private function remplirChpNomComplet() {
574
		echo "---- Attribution du champ nom complet au taxons :\n";
575
		$requete = "UPDATE {$this->table} SET nom_complet = CONCAT(nom_sci,' ',auteur)";
576
		$resultat = $this->getBdd()->requeter($requete);
577
		if ($resultat === false) {
578
			echo "Erreur de génération du champ nom complet\n";
579
		} else {
580
			echo "OK\n";
581
		}
582
	}
583
 
584
	private function genererChpFamille() {
585
		$this->preparerTablePrChpFamille();
586
		$resultats = $this->recupererTuplesPrChpFamille();
587
		$noms = array();
588
		$introuvables = array();
589
		$introuvablesSyno = array();
590
		foreach ($resultats as $id => $nom) {
591
			$nn = $nom['num_nom'];
592
			$nnr = $nom['num_nom_retenu'];
593
			$nts = $nom['num_tax_sup'];
594
			$rg = $nom['rang'];
595
			if ($nnr != '') {
596
				if ($rg == '180') {
597
					$noms[$nn] = $nom['nom_sci'];
598
				} else {
599
					if ($nn == $nnr) {// nom retenu
600
						if (isset($noms[$nts])) {
601
							$noms[$nn] = $noms[$nts];
602
						} else {
603
							$introuvables[] = $nn;
604
						}
605
					} else {// nom synonyme
606
						if (isset($noms[$nnr])) {
607
							$noms[$nn] = $noms[$nnr];
608
						} else {
609
							$introuvablesSyno[] = $nom;
610
						}
611
					}
612
				}
613
			}
614
			unset($resultats[$id]);
615
			$this->afficherAvancement("Attribution de leur famille aux noms en cours");
616
		}
617
		echo "\n";
618
 
619
		foreach ($introuvablesSyno as $id => $nom) {
620
			$nn = $nom['num_nom'];
621
			$nnr = $nom['num_nom_retenu'];
622
			if (isset($noms[$nnr])) {
623
				$noms[$nn] = $noms[$nnr];
624
			} else {
625
				$introuvables[] = $nn;
626
			}
627
			unset($introuvablesSyno[$id]);
628
			$this->afficherAvancement("Attribution de leur famille aux synonymes en cours");
629
		}
630
		echo "\n";
631
 
632
		if (count($introuvables) > 0) {
633
			echo count($introuvables) . ' familles sont introuvables : ' . implode(',', $introuvables) . "\n";
634
		}
635
		$this->remplirChpFamille($noms);
636
	}
637
 
638
	private function preparerTablePrChpFamille() {
639
		$requete = "SHOW COLUMNS FROM {$this->table} LIKE 'famille' ";
640
		$resultat = $this->getBdd()->recuperer($requete);
641
		if ($resultat === false) {
642
			$requete = 	"ALTER TABLE {$this->table} ".
643
				'ADD famille VARCHAR(255) '.
644
				'CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ';
645
			$this->getBdd()->requeter($requete);
646
		}
647
	}
648
 
649
	private function recupererTuplesPrChpFamille() {
650
		$requete = 'SELECT num_nom, num_nom_retenu, num_tax_sup, rang, nom_sci '.
651
			"FROM {$this->table} ".
652
			"WHERE rang >= 180 ".
653
			"ORDER BY rang ASC, num_tax_sup ASC, num_nom_retenu DESC ";
654
		$resultat = $this->getBdd()->recupererTous($requete);
655
		return $resultat;
656
	}
657
 
658
	private function remplirChpFamille($noms) {
659
		foreach ($noms as $id => $famille) {
660
			$famille = $this->getBdd()->proteger($famille);
661
			$requete = "UPDATE {$this->table} SET famille = $famille WHERE num_nom = $id ";
662
			$resultat = $this->getBdd()->requeter($requete);
663
			if ($resultat === false) {
664
				throw new Exception("Erreur d'insertion pour le tuple $id");
665
			}
666
			$this->afficherAvancement("Insertion des noms de famille dans la base en cours");
667
		}
668
		echo "\n";
669
	}
670
 
671
	private function genererChpHierarchie() {
672
		$this->preparerTablePrChpHierarchie();
673
		$table = Config::get('tables.isfan');
674
 
675
		$requete = "UPDATE {$this->table} SET hierarchie = NULL ";
676
		$mise_a_jour = $this->getBdd()->requeter($requete);
677
 
678
		$requete_hierarchie = "SELECT num_nom, num_nom_retenu, num_tax_sup FROM " . $this->table . " ORDER BY rang DESC";
679
 
680
		$resultat = $this->getBdd()->recupererTous($requete_hierarchie);
681
		$num_nom_a_num_sup = array();
682
		foreach($resultat as &$taxon) {
683
			$num_nom_a_num_sup[$taxon['num_nom']] = $taxon['num_tax_sup'];
684
		}
685
		$chemin_taxo = "";
686
		foreach($resultat as &$taxon) {
687
			$chemin_taxo = $this->traiterHierarchieNumTaxSup($taxon['num_nom_retenu'], $num_nom_a_num_sup).'-';
688
			$requete = "UPDATE {$this->table} SET hierarchie = ".$this->getBdd()->proteger($chemin_taxo)." WHERE num_nom = ".$taxon['num_nom']." ";
689
			$mise_a_jour = $this->getBdd()->requeter($requete);
690
			$this->afficherAvancement("Insertion de la hierarchie taxonomique en cours");
691
		}
692
		echo "\n";
693
	}
694
 
695
	private function traiterHierarchieNumTaxSup($num_nom_retenu, &$num_nom_a_num_sup) {
696
		$chaine_hierarchie = "";
697
		if(isset($num_nom_a_num_sup[$num_nom_retenu])) {
698
			$num_tax_sup = $num_nom_a_num_sup[$num_nom_retenu];
699
			$chaine_hierarchie = '-'.$num_tax_sup;
700
			if($num_tax_sup != 0 && $num_tax_sup != '') {
701
				$chaine_hierarchie = $this->traiterHierarchieNumTaxSup($num_tax_sup, $num_nom_a_num_sup).$chaine_hierarchie;
702
			}
703
		}
704
		return $chaine_hierarchie;
705
	}
706
 
707
	private function preparerTablePrChpHierarchie() {
708
		$requete = "SHOW COLUMNS FROM {$this->table} LIKE 'hierarchie' ";
709
		$resultat = $this->getBdd()->recuperer($requete);
710
		if ($resultat === false) {
711
			$requete = 	"ALTER TABLE {$this->table} ".
712
						'ADD hierarchie VARCHAR(1000) '.
713
						'CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ';
714
			$this->getBdd()->requeter($requete);
715
		}
716
	}
717
}
718
?>