Subversion Repositories eFlore/Applications.cel

Rev

Rev 3755 | Rev 3761 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
3755 killian 1
<?php
2
 
3
/*
4
	PHP 7
5
 
6
	Script used to synchronize PN occ with CEL
7
*/
8
 
9
class PullPlantnet extends Script {
10
 
11
	protected $bdd;
12
 
13
	protected $allowedPartners = ['tb', 'pn'];
14
 
15
	// Nom du fichier contenant les correspondances d'ID TB/PN
16
	protected $correspondingIdsFilename = '';
17
 
18
	// Cache d'informations utilisateurs provenant de l'annuaire TB
19
	protected $userInfos = [];
20
 
3757 killian 21
	// Cache des obs id PN traitées pendant cette run
22
	protected $processedObsId = [];
23
 
3755 killian 24
	// Paramètre de suivi et de pagination de l'API des obs PN
25
	protected $startDate = '';
26
	protected $currentPage = '';
27
	protected $currentProject = '';
28
	protected $hasMore = false;
29
	protected $count = 0;
30
 
31
	// Traduction des organes de PN
32
	protected $tagsImageTraduits = [
33
		'flower' => 'fleur',
34
		'fruit' => 'fruit',
35
		'leaf' => 'feuille',
36
		'bark' => 'écorce',
37
		'branch' => 'branche',
38
		'habit' => 'port',
39
	];
40
 
41
	/**
42
	 * Paramêtres par défaut disponibles pour la ligne de commande
43
	 * le tableau se construit de la forme suivante :
44
	 * - clé =  nom du paramêtre '-foo'
45
	 * - value = contient un nouveau tableau composé de cette façon :
46
	 *  - booléen: true si le paramêtre est obligatoire
47
	 *  - booléen ou var : true si le paramêtre nécessite un valeur à sa suite ou la valeur par défaut
48
	 *  - string: description du contenu du paramêtre
49
	 * Les paramêtres optionels devraient être déclaré à la fin du tableau.
50
	 * Le dernier parametre du tableau peut avoir la valeur '...',
51
	 * il contiendra alors l'ensemble des paramêtres suivant trouvés sur la ligne de commande.
52
	 * @var array
53
	 */
54
	protected $parametres_autorises = array(
55
		'-startDate' => array(false, '1', 'Date de début (parsée par strtotime). Ex: "YYYY:MM:DD HH:II:SS"'),
56
		'-pnObsId' => array(false, true, "ID de l'obs chez PlantNet"),
57
		'-tbObsId' => array(false, true, "ID de l'obs chez Tela"),
58
	);
59
 
60
	public function __construct($script_nom, $parametres_cli) {
61
		parent::__construct($script_nom, $parametres_cli);
62
		$this->bdd = new Bdd();
63
 
64
		$this->correspondingIdsFilename = Config::get('correspondingIdsFilename');
65
	}
66
 
67
	public function executer() {
68
		$cmd = $this->getParametre('a');
69
 
70
		switch ($cmd) {
71
			case 'updateLatest':
72
				$this->updateLatest($this->getParametre('startDate'));
73
				break;
74
			case 'updateOnePN':
75
				$this->updateOne($this->getParametre('pnObsId'));
76
				break;
77
			case 'updateOneTB':
78
				$this->updateOneTB($this->getParametre('tbObsId'));
79
				break;
80
			case 'updateCorrespondingIdsTable':
81
				$this->updateCorrespondingIdsTable();
82
				break;
83
			default:
84
				$msg = "Erreur : la commande '$cmd' n'existe pas!\n"
85
						. ', utilisez plutôt :' . "\n"
86
						. 'php cli.php PullPlantnet -a updateLatest -startDate "YYYY:MM:DD HH:II:SS"' . "\n"
87
						. 'php cli.php PullPlantnet -a updateOnePN -pnObsId "xxxxxx"' . "\n"
88
						. 'php cli.php PullPlantnet -a updateOneTB -tbObsId "xxxxxx"' . "\n"
89
						. 'php cli.php PullPlantnet -a updateCorrespondingIdsTable' . "\n"
90
						;
91
				throw new Exception($msg);
92
		}
93
	}
94
 
95
	/**
96
	 * Considering all modified pn obs since startDate
97
	 * One pn project after an other
98
	 * Inserting obs in tb db (if new and matching user email)
99
	 */
100
	private function updateLatest(string $startDate = '1917:03:15 00:00:00') {
101
		$this->startDate = strtotime($startDate) * 1000; // we need a microtimestamp
102
 
103
		$pnProjects = $this->getProjects(); // refresh projects list
104
		foreach ($pnProjects as $project) {
105
			do {
106
				$observations_PN = $this->getProjectLatest($project);
107
				$this->updateObs($observations_PN);
108
			} while ($this->hasMore);
109
		}
110
	}
111
 
112
	private function getProjectLatest(array $project): array {
113
		$this->currentProject = $project;
114
 
115
		if (!$this->currentPage) {
116
			echo 'Projet ' . $project['name'] . "\n";
117
 
118
			// hop, on appelle le service de PN
119
			$url_service = str_replace(
120
				['{project}', '{token}', '{startDate}'],
121
				[$project['id'], Config::get('tokenPlantnet'), $this->startDate],
122
				Config::get('urlPlantnetBase').Config::get('urlPlantnetLatestChanges')
123
			);
124
			// die(var_dump($url_service));
125
			$this->currentPage = $url_service;
126
		}
127
 
128
		$ch = curl_init($this->currentPage);
129
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
130
		$reponse = curl_exec($ch);
131
		$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
132
		curl_close($ch);
133
 
134
		// cool, maintenant on va trier ce qu'on a reçu
135
		if (!$reponse) {
136
			throw new Exception("\nPN ne répond rien à l'adresse {$this->currentPage}\n");
137
		} elseif (200 != $code) {
138
			// l'api répond avec une 404 quand y'a une date dans le futur ou simplement pas de nouvelle obs...
139
			if (404 == $code && strpos($reponse, 'No more results')) {
140
				$this->hasMore = false;
141
				$this->currentPage = '';
142
				return [];
143
			}
144
			throw new Exception("\nPN répond avec une $code à l'adresse {$this->currentPage} : $reponse\n");
145
		}
146
		$responseJson = json_decode($reponse, true);
147
		$observations_PN = $responseJson['data'] ?? [];
148
 
149
		$this->hasMore = $responseJson['hasMore'];
150
		if ($this->hasMore) {
151
			$this->count += count($observations_PN);
152
			$this->currentPage = Config::get('urlPlantnetBase').$responseJson['next'].$this->count;
153
		} else {
154
			$this->currentPage = '';
155
			$this->count = 0;
156
		}
157
 
158
		return $observations_PN;
159
	}
160
 
161
	private function getProjects(): array {
162
		// get PN projects list
163
		$url = str_replace('{token}', Config::get('tokenPlantnet'), Config::get('urlPlantnetBase').Config::get('urlPlantnetProjects'));
164
 
165
		$ch = curl_init($url);
166
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
167
		$reponse = curl_exec($ch);
168
		$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
169
		curl_close($ch);
170
 
171
		if (!$reponse || 200 != $code) {
172
			throw new Exception("\nPN répond avec une $code à l'adresse $url_service : $reponse\n");
173
		}
174
		$pnProjects = json_decode($reponse, true);
175
 
176
		echo 'Liste de projets récupérée : ' . count($pnProjects) . " projets dans la liste\n";
177
 
178
		return $pnProjects;
179
	}
180
 
181
	/**
182
	 * For a given bunch of plantnet obs, post new one threw saisie widget service
183
	 */
184
	private function updateObs(array $observations_PN) {
185
 
186
		$url_cel_widget_saisie = Config::get('urlCelWidgetSaisie');
187
 
188
		foreach ($observations_PN as $obs) {
3757 killian 189
			// est-ce qu'on a déjà traité cette obs ? (oui une même obs peut être dans plusieurs projects)
190
			if (in_array($obs['id'], $this->processedObsId)) {
191
				continue;
192
			} else {
193
				$this->processedObsId[] = $obs['id'];
194
			}
195
 
3755 killian 196
			// on ne teste pas la suppression de l'obs ici, faut le faire après avoir vérifié si on l'a déjà synchro
197
			if (!isset($obs['currentName'])) {
198
				continue; // pas de nom de taxon, obs inutile
199
			}
200
			if (!isset($obs['geo'])) {
201
				continue; // pas de position, obs inutile
202
			}
203
			if (!isset($obs['dateObs'])) {
204
				continue; // pas de date, obs inutile
205
			}
206
 
207
			if (isset($obs['partner']['id']) && 'tela' === $obs['partner']['id']) {
208
				// c'est une obs tela
209
				// si c'est mis à jour récemment coté PN et qu'on l'a pas supprimée chez nous entre temps
210
					// on update les votes PN
211
					// on update l'identification proposée par PN
212
 
213
				// @TODO
214
				continue;
215
			} elseif (!isset($obs['partner']['id'])) {
216
				// ce n'est pas une obs d'un partenaire, c'est donc une obs PN
217
				// on récupère l'id utilisateur tela via son mail
218
				$email = $obs['author']['email'];
219
				$infos_utilisateur = $this->findUserInfo($email);
220
				if (!$infos_utilisateur) {
221
					continue; // c'est pas un telabotaniste
222
				}
223
				echo "Synchro d'une obs d'un telabotaniste : $email\n";
224
				// echo json_encode($obs);
225
				// die(var_dump($obs));
226
 
227
				// vérification que l'obs n'a pas déjà été ajoutée à la BdD de Tela
228
				$sql = "SELECT date_maj, id_observation FROM cel_plantnet WHERE id_plantnet = '{$obs['id']}'"
229
						. ' -- ' . __FILE__ . ':' . __LINE__;
230
				$res = $this->bdd->recupererTous($sql);
231
				// die(var_dump($res));
232
				if ($res) {
233
					// l'obs existe déjà, on vérifie si il faut màj puis on passe à la suite
234
					// la date de l'obs est un microtime, donc on coupe les millièmes
235
					// die(var_dump((int)($obs['dateUpdated']/1000), strtotime($res[0]['date_maj'])));
236
					if ((int)($obs['dateUpdated']/1000) > strtotime($res[0]['date_maj'])) {
237
						echo "Obs déjà en base, mise à jour (TB {$res[0]['id_observation']})\n";
238
						$this->updateFromPN($obs, $res[0]['id_observation']);
239
					} else {
240
						echo "Obs déjà en base : ID PN {$obs['id']}, ID TB {$res[0]['id_observation']}\n";
241
					}
242
					continue;
243
				}
244
 
245
				if (isset($obs['deleted']) && (true === $obs['deleted'])) {
246
					continue; // obs supprimée chez PN sans être passée par nos serveurs
247
				}
248
 
249
				$images = [];
250
				$tags_images = [];
251
				foreach ($obs['images'] ?? [] as $i => $image) {
252
					if ($image['deleted']) {
253
						continue;
254
					}
255
 
256
					// téléchargement de l'image PN
257
					$tempfile = tempnam("/tmp", "PullPN_") . ".jpg";
258
					$handle = fopen($tempfile, "w");
259
					fwrite($handle, file_get_contents($image['o']));
260
					fclose($handle);
261
 
262
					echo "cool on a fait un fichier de " . filesize($tempfile) . " octets là : $tempfile\n";
263
 
264
					$params = [
265
						'name' => 'image' . $i,
266
						'fichier' => new CURLFile($tempfile, 'image/jpg')
267
					];
268
 
269
					// envoi de l'image PN à l'api de création
270
					$ch = curl_init(Config::get('urlCelUploadImageTemp'));
271
					curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
272
					curl_setopt($ch, CURLOPT_POST, true);
273
					curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
274
					$reponse = curl_exec($ch);
275
					// var_dump($reponse);
276
					$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
277
					curl_close($ch);
278
 
279
					unlink($tempfile);
280
 
281
					$reponse = simplexml_load_string($reponse);
282
					/* Response format if success:
283
					<?xml version="1.0" encoding="UTF-8"?>
284
					<root>
285
						<miniature-url>https://api-test.tela-botanica.org/tmp/cel/imgtmp/chaflipe_min.jpg</miniature-url>
286
						<image-nom>chaflipe.jpg</image-nom>
287
						<message></message>
288
						<debogage></debogage>
289
					</root>
290
					*/
291
					// var_dump($reponse);
292
					if ($reponse && '' == $reponse->message /* && '' != $reponse->{'image-nom'} */) {
293
						$images[] = (string)$reponse->{'image-nom'};
294
						$tags_images[] = $this->tagsImageTraduits[$image['organ']] ?? ''; // @TODO translate
295
					}
296
				}
297
				// var_dump($images, $tags_images);
298
				// die();
299
 
300
				// on insère l'obs via le service CelWidgetSaisie
301
				$infos_obs = [
302
					// 'obsId1[commune_code_insee]' => '',
303
					'obsId1[commune_nom]' => $obs['geo']['place'] ?? '',
304
					'obsId1[date]' => date('d/m/Y', intdiv($obs['dateObs'], 1000)),
305
					// 'obsId1[famille]' => '',
306
					'obsId1[latitude]' => (string)$obs['geo']['lat'] ?? '',
307
					// 'obsId1[lieudit]' => '',
308
					'obsId1[longitude]' => (string)$obs['geo']['lon'] ?? '',
309
					// 'obsId1[milieu]' => '',
310
					// 'obsId1[nom_ret]' => '',
311
					'obsId1[nom_sel]' => $obs['currentName'],
312
					'obsId1[certitude]' => 'douteux',
313
					// 'obsId1[notes]' => '',
314
					// 'obsId1[num_nom_ret]' => '',
315
					// 'obsId1[num_nom_sel]' => '',
316
					// 'obsId1[num_taxon]' => '',
317
					'obsId1[referentiel]' => $this->findProbableTaxoRepos($this->currentProject['id']),
318
					// 'obsId1[station]' => '',
319
					'obsId1[obs_id]' => $obs['id'],
320
					'projet' => 'PlantNet',
321
					'tag-img' => implode(', ', $tags_images ?? []),
322
					'tag-obs' => 'plantnet, plantnet-mobile, pn:referentiel-' . $this->currentProject['id'],
323
					'utilisateur[courriel]' => $email,
324
					'utilisateur[id_utilisateur]' => $infos_utilisateur['id'],
325
					'utilisateur[nom]' => $infos_utilisateur['nom'],
326
					'utilisateur[prenom]' => $infos_utilisateur['prenom'],
327
					'origin' => 'pullPlantnet',
328
				];
329
 
330
				foreach ($images as $i => $image) {
331
					$infos_obs["obsId1[image_nom][$i]"] = $image;
332
				}
333
				// die(var_dump($infos_obs));
334
 
335
				// curl post $infos_obs
336
				$ch = curl_init($url_cel_widget_saisie);
337
				curl_setopt($ch, CURLOPT_POST, true);
338
				curl_setopt($ch, CURLOPT_POSTFIELDS, $infos_obs);
339
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
340
				$reponse = curl_exec($ch);
341
				$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
342
				curl_close($ch);
343
 
344
				if (!$reponse || 200 != $code) {
345
					throw new Exception("Ça a pété à l'envoi de l'obs :\n $reponse\n avec l'obs : " . json_encode($infos_obs) . "\n");
346
				}
347
 
348
				// var_dump($reponse);
349
				$id_obs_tb = $this->bdd->proteger(json_decode($reponse, true)['id']);
350
				$id_obs_pn = $this->bdd->proteger($obs['id']);
351
				// on insère les ids de correspondance obsPN obsTB dans la table cel_plantnet
352
				$sql = 'INSERT INTO cel_plantnet (id_observation, id_plantnet, date_maj)'
353
						.' VALUES (%s, %s, NOW())'
354
						. ' -- ' . __FILE__ . ':' . __LINE__;
355
				$sql = sprintf($sql, $id_obs_tb, $id_obs_pn);
356
				$this->bdd->requeter($sql);
357
			}
358
		}
359
	}
360
 
361
	/**
362
	 * Return TB taxo repos names for given PN project
363
	 *
364
	 * @return string
365
	 */
366
	private function findProbableTaxoRepos($pnProjectId) {
367
		$selectedRepos = [];
368
		// Référentiels tela botanica indexés par référentiels PN (version octobre 2019)
369
		// @TODO à revoir en fonction des nouvelles mises en prod de nouveaux référentiels
370
		$tbTaxoRepos = [
371
			'afn' => [/*'apd', */'isfan'],
372
			'aft' => ['apd'],
373
			'antilles' => ['bdtxa', 'taxref'],
374
			'canada' => ['vascan'],
375
			'comores' => ['apd'],
376
			'endemia' => ['florical', 'taxref'],
377
			'taxref	' => ['bdtfx'],
378
			'guyane' => ['aublet', 'taxref'],
379
			'hawai' => [],
380
			'lapaz' => ['aublet', 'taxref'],
381
			'martinique' => ['bdtxa', 'taxref'],
382
			'maurice' => ['apd'],
383
			'medor' => ['lbf'],
384
			'namerica' => [],
385
			'polynesiefr' => ['taxref'],
386
			'prosea' => ['asia'],
387
			'prota' => ['isfan', 'apd'],
388
			'provence' => ['bdtfx', 'taxref'],
389
			'reunion' => ['bdtre', 'taxref'],
390
			'salad' => ['bdtfx', 'taxref'],
391
			'useful' => [],
392
			'weurope' => ['bdtfx'],
393
			'the-plant-list' => [],
394
			'iscantree' => ['apd'],
395
			'central-america' => [],
396
			'invasion' => ['bdtfx'],
397
			'weeds' => ['bdtfx'],
398
			'malaysia' => [],
399
		];
400
 
401
		if (array_key_exists($pnProjectId, $tbTaxoRepos)) {
402
			array_map(function($repo) use ($selectedRepos) {
403
				$selectedRepos[] = $repo;
404
			}, $tbTaxoRepos[$pnProjectId]);
405
		}
406
 
407
		// @TODO chercher le nom dans plusieurs référentiels avant d'envoyer l'obs
408
		// prendre "enrichirDonneesTaxonomiques" du service de saisie et le coller ici
409
		// en attendant on envoi juste le premier référentiel trouvé
410
		return $selectedRepos[0] ?? '';
411
	}
412
 
413
	/*
414
	 * Retrouve les infos d'un utilisateur tela à partir de son email
415
	 * @param string $email User email
416
	 * @return mixed 		Tableau des infos de l'utilisateur
417
	 *						False si l'email n'est pas trouvé dans l'annuaire
418
	 */
419
	private function findUserInfo($email) {
420
		// cherche dans le cache
421
		if (array_key_exists($email, $this->userInfos)) {
422
			$infosUtilisateur = $this->userInfos[$email];
423
			// echo("Email in cache : $email\n");
424
		} else {
425
			$infosUtilisateur = false;
426
			$urlInfosUtilisateur = str_replace('{email}', $email, Config::get('urlAnnuaireIdParEmail'));
427
 
428
			$ch = curl_init($urlInfosUtilisateur);
429
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
430
			$reponse = curl_exec($ch);
431
			$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
432
			curl_close($ch);
433
 
434
			// on peut pas tester le code de réponse de cette api, si l'utilisateur n'est pas trouvé ça fait une 500 >_<
435
			// une bonne réponse ressemble à ça :
436
			// {"killian@tela-botanica.org":{"id":"30489","prenom":"Killian","nom":"Stefanini","pseudo":"Killian Stefanini","pseudoUtilise":true,"intitule":"Killian Stefanini","avatar":"\/\/www.gravatar.com\/avatar\/a9b9b8484076540924c03af816c77fc8?s=50&r=g&d=mm","groupes":{"19226":"adm","18943":"","23152":"","21684":"","21598":"adm","23184":"","23516":""},"permissions":["editor"],"nomWiki":"KillianStefanini"}}
437
			$reponse = json_decode($reponse, true);
438
			if (!isset($reponse)) {
439
				throw new Exception("\nL'annuaire n'a pas répondu avec du json : code $code à l'adresse $urlInfosUtilisateur : $reponse\n");
440
			}
441
 
442
			if (!isset($reponse['error'])) {
443
				$infosUtilisateur = array_shift($reponse);
444
			}
445
 
446
			// met en cache
447
			$this->userInfos[$email] = $infosUtilisateur;
448
			// echo("Email cached : $email\n");
449
		}
450
 
451
		return $infosUtilisateur;
452
	}
453
 
454
	private function updateFromPN(array $pnObs, string $tbObsId) {
455
		if (!is_array($pnObs) || !is_string($tbObsId)) {
456
			// die(var_dump($pnObs, $tbObsId));
457
			throw new Exception("\nBad params types\n");
458
		}
459
		// die(var_dump($pnObs));
460
 
461
		// check for deleted
462
		if (isset($pnObs['deleted']) && (true === $pnObs['deleted'])) {
463
			// est-ce une obs issue de PN ?
464
			//// faut regarder le champ input_source == PlantNet
465
			$sql = "SELECT input_source FROM occurrence WHERE id = '$tbObsId'"
466
					. ' -- ' . __FILE__ . ':' . __LINE__;
467
			$res = $this->bdd->recupererTous($sql);
468
			die(var_dump($res));
469
			if (isset($res[0]) && ('PlantNet' === $res[0]['input_source'])) {
470
				// oui ? alors supprimer obs !
471
				echo("obs à supprimer\n");
472
				$sql = "DELETE FROM occurrence WHERE id = '$tbObsId'"
473
						. ' -- ' . __FILE__ . ':' . __LINE__;
474
				$this->bdd->requeter($sql);
475
				$sql = "UPDATE photos SET occurrence_id = NULL WHERE occurrence_id = '$tbObsId'"
476
						. ' -- ' . __FILE__ . ':' . __LINE__;
477
				$this->bdd->requeter($sql);
478
			}
479
		}
480
 
481
		// check for deleted images
482
		foreach ($pnObs['images'] as $image) {
483
			if ($image['deleted']) {
484
				// no idea
485
				// y'a pas encore de lien tangible entre les images PN et les notres
486
			}
487
		}
488
 
489
		// @TODO : finir la comparaison des proposition entre celles de Tela et celles PN
490
		// // check for votes (notes et taxon)
491
		// $names = [];
492
		// foreach ($pnObs['computed']['votes'] as $vote) {
493
		// 	echo($vote['name']);
494
		// 	echo($vote['score']['pn']);
495
		// 	echo($vote['score']['total']);
496
 
497
		// 	$names[$vote['score']['pn']] = $vote['name'];
498
		// }
499
		// ksort($names, SORT_NUMERIC); // votes sorted by score asc
500
		// $pn_sorted_votes = array_reverse($names, true); // desc
501
 
502
		// // get existing votes
503
		// $sql = "SELECT id_commentaire, nom_sel, nom_sel_nn, nom_referentiel, nom_referentiel, utilisateur_courriel, proposition_initiale, proposition_retenue"
504
		// 		. "WHERE ce_observation = '$tbObsId' AND ce_commentaire_parent = 0"
505
		// 		. ' -- ' . __FILE__ . ':' . __LINE__;
506
		// $existing_votes = $this->bdd->recupererTous($sql);
507
 
508
		// // @TODO : compare votes
509
		// // insert_new_votes($pn_sorted_votes, $existing_votes);
510
	}
511
 
512
	private function updateOnePN($id) {
513
		// vérification que l'obs est bien dans la BdD de Tela
514
		$sql = "SELECT date_maj, id_observation FROM cel_plantnet WHERE id_plantnet = '$id'"
515
					. ' -- ' . __FILE__ . ':' . __LINE__;
516
		$res = $this->bdd->recupererTous($sql);
517
		// die(var_dump($res));
518
		if (!$res) {
519
			throw new Exception("\nPlantnet occurrence id ($id) doesn't exist in tela db. \n");
520
		}
521
 
522
		// l'obs existe déjà à Tela, on vérifie si il faut màj
523
		$urlInfosObs = str_replace(
524
			['{token}', '{ids}'],
525
			[Config::get('tokenPlantnet'), $id],
526
			Config::get('urlPlantnetBase').Config::get('urlPlantnetObsById')
527
		);
528
		$ch = curl_init($urlInfosObs);
529
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
530
		$reponse = curl_exec($ch);
531
		$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
532
		curl_close($ch);
533
 
534
		if (!$reponse || 200 != $code) {
535
			throw new Exception("\nPlantnet api ($urlInfosObs) replied with code $code : $reponse\n");
536
		}
537
 
538
		echo "La suite n'a pas été implémentée.\n";
539
		die(var_dump($reponse));
540
	}
541
 
542
	private function updateOneTB($id) {
543
		$corres = $this->findMatchingPartnerId($id, 'tb');
544
		echo "L'obs tela avec l'id $id a été trouvée chez plantnet avec l'id : " .$corres['pn'] . "\n";
545
		echo "La suite n'a pas été implémentée.\n";
546
	}
547
 
548
	/*
549
	 * Trouve les ids d'une obs chez les partenaires
550
	 * Il faut lancer updateMatchingPartnersIds pour obtenir une liste fraiche
551
	 *
552
	 * @param 	string $id			L'id de l'obs
553
	 * @param 	string $partner		Le partenaire correspondant à l'id de l'obs
554
	 *
555
	 * @return  mixed 				Le tableau de correspondances d'ids
556
	 *								False si l'id n'est pas trouvé
557
	 */
558
	private function findMatchingPartnerId($id, $partner) {
559
		if (!in_array($partner, $this->allowedPartners)) {
560
			throw new Exception("\nUnknown partner : $partner. Available Partners : " . implode(', ', $this->allowedPartners) . "\n");
561
		}
562
 
563
		// le json ressemble à ça :
564
		// {"tb":"2369732","pn":"1001020199"}, {"tb":"2369733","pn":"1001020176"}, ...
565
		$ids = json_decode(file_get_contents($this->correspondingIdsFilename), true);
566
		// extrait la colonne du partenaire recherché du tableau multidimensionnel fraichement décodé
567
		$partnerColumn = array_column($ids, $partner);
568
		// cherche l'index de l'id recherché
569
		$index = array_search($id, $partnerColumn);
570
 
571
		return $index ? $ids[$index] : false;
572
	}
573
 
574
	private function updateCorrespondingIdsTable() {
575
		// first update cache file if necessary
576
		if (!file_exists($this->correspondingIdsFilename) || time() > (filemtime($this->correspondingIdsFilename) + (24 * 3600))) {
577
			$this->updateMatchingPartnersIds();
578
		}
579
 
580
		$data = file_get_contents($this->correspondingIdsFilename);
581
		$data = json_decode($data, true);
582
 
583
		$now = new DateTime;
584
		$now = $this->bdd->proteger($now->format('Y-m-d H:i:s'));
585
 
586
		$sqlInsert = 'INSERT INTO cel_plantnet (id_observation, id_plantnet, date_maj)'
587
					. ' VALUES %s'
588
					. ' ON DUPLICATE KEY UPDATE id_observation=VALUES(id_observation), id_plantnet=VALUES(id_plantnet)'
589
					. ' -- ' . __FILE__ . ':' . __LINE__;
590
		$values = '';
591
 
592
		foreach ($data as $id => $corres) {
593
			$id_obs_tb = $this->bdd->proteger($corres['tb']);
594
			$id_obs_pn = $this->bdd->proteger($corres['pn']);
595
			// on insère les ids de correspondance obsPN obsTB dans la table cel_plantnet
596
			$values .= " ($id_obs_tb, $id_obs_pn, $now),";
597
 
598
			if (0 === $id % 100) {
599
				$values = substr($values, 0, -1); // retire la dernière virgule
600
				$sql = sprintf($sqlInsert, $values);
601
				// var_dump($sql);
602
				$this->bdd->requeter($sql);
603
				$values = '';
604
			}
605
		}
606
		// Faut envoyer les dernières données qui sont pas passées dans le modulo
607
		$values = substr($values, 0, -1); // retire la dernière virgule
608
		$sql = sprintf($sqlInsert, $values);
609
		// var_dump($sql);
610
		$this->bdd->requeter($sql);
611
 
612
	}
613
 
614
	private function updateMatchingPartnersIds() {
615
		// curl -X GET --header 'Accept: application/json' 'https://bourbonnais.cirad.fr:8081/v1/edi/observations/partnerids?token=f0ca433febe320675c24ee2ddfab8b82f65d556b' > partnerids.txt
616
		$matchingPartnersIdsServiceUrl = str_replace(
617
			'{token}',
618
			Config::get('tokenPlantnet'),
619
			Config::get('urlPlantnetBase').Config::get('urlPlantnetMatchingPartner')
620
		);
621
		$ch = curl_init($matchingPartnersIdsServiceUrl);
622
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
623
 
624
		echo "Updating matching partners ids...\n";
625
		$reponse = curl_exec($ch);
626
		$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
627
		curl_close($ch);
628
 
629
 
630
		if (!$reponse || 200 != $code) {
631
			throw new Exception("\nError updating partners ids, http error code \"$code\" whith url \"$matchingPartnersIdsServiceUrl\"...\n");
632
		}
633
		echo "Response data from PN api gathered, know computing...\n";
634
 
635
		if (!file_put_contents($this->correspondingIdsFilename, $reponse)) {
636
			throw new Exception("\nError writing correspondingIdsFilename with path : " . $this->correspondingIdsFilename . "\n");
637
		}
638
		echo "Matching partners ids saved!";
639
	}
640
}