Subversion Repositories eFlore/Applications.cel

Rev

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