Subversion Repositories eFlore/Applications.cel

Rev

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