Subversion Repositories eFlore/Applications.cel

Rev

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