Subversion Repositories eFlore/Applications.cel

Rev

Rev 3757 | Rev 3762 | 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
258
					$tempfile = tempnam("/tmp", "PullPN_") . ".jpg";
259
					$handle = fopen($tempfile, "w");
260
					fwrite($handle, file_get_contents($image['o']));
261
					fclose($handle);
262
 
3761 killian 263
					echo "Image de " . number_format(filesize($tempfile), 0, ',', ' ') . " octets créé : $tempfile\n";
3755 killian 264
 
265
					$params = [
266
						'name' => 'image' . $i,
267
						'fichier' => new CURLFile($tempfile, 'image/jpg')
268
					];
269
 
270
					// envoi de l'image PN à l'api de création
271
					$ch = curl_init(Config::get('urlCelUploadImageTemp'));
272
					curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
273
					curl_setopt($ch, CURLOPT_POST, true);
274
					curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
275
					$reponse = curl_exec($ch);
276
					// var_dump($reponse);
277
					$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
278
					curl_close($ch);
279
 
280
					unlink($tempfile);
281
 
282
					$reponse = simplexml_load_string($reponse);
283
					/* Response format if success:
284
					<?xml version="1.0" encoding="UTF-8"?>
285
					<root>
286
						<miniature-url>https://api-test.tela-botanica.org/tmp/cel/imgtmp/chaflipe_min.jpg</miniature-url>
287
						<image-nom>chaflipe.jpg</image-nom>
288
						<message></message>
289
						<debogage></debogage>
290
					</root>
291
					*/
292
					// var_dump($reponse);
293
					if ($reponse && '' == $reponse->message /* && '' != $reponse->{'image-nom'} */) {
294
						$images[] = (string)$reponse->{'image-nom'};
295
						$tags_images[] = $this->tagsImageTraduits[$image['organ']] ?? ''; // @TODO translate
296
					}
297
				}
298
				// var_dump($images, $tags_images);
299
				// die();
300
 
3761 killian 301
				$geo = $this->getGeoInfo($obs['geo']);
302
 
3755 killian 303
				// on insère l'obs via le service CelWidgetSaisie
304
				$infos_obs = [
3761 killian 305
					'obsId1[date]' => date('d/m/Y', intdiv($obs['dateObs'], 1000)),
306
					'obsId1[latitude]' => $geo['lat'] ?? null,
307
					'obsId1[longitude]' => $geo['lon'] ?? null,
308
					'obsId1[pays]' => $geo['countryCode'] ?? null,
309
					'obsId1[code_postal]' => $geo['postcode'] ?? null,
310
					'obsId1[commune_nom]' => $geo['city'] ?? null,
3755 killian 311
					// 'obsId1[commune_code_insee]' => '',
312
					// 'obsId1[lieudit]' => '',
313
					// 'obsId1[milieu]' => '',
3761 killian 314
					'obsId1[nom_sel]' => $obs['currentName'],
3755 killian 315
					// 'obsId1[nom_ret]' => '',
3761 killian 316
					// 'obsId1[famille]' => '',
3755 killian 317
					'obsId1[certitude]' => 'douteux',
318
					// 'obsId1[notes]' => '',
319
					// 'obsId1[num_nom_ret]' => '',
320
					// 'obsId1[num_nom_sel]' => '',
321
					// 'obsId1[num_taxon]' => '',
322
					'obsId1[referentiel]' => $this->findProbableTaxoRepos($this->currentProject['id']),
323
					// 'obsId1[station]' => '',
324
					'obsId1[obs_id]' => $obs['id'],
325
					'projet' => 'PlantNet',
326
					'tag-img' => implode(', ', $tags_images ?? []),
327
					'tag-obs' => 'plantnet, plantnet-mobile, pn:referentiel-' . $this->currentProject['id'],
328
					'utilisateur[courriel]' => $email,
329
					'utilisateur[id_utilisateur]' => $infos_utilisateur['id'],
330
					'utilisateur[nom]' => $infos_utilisateur['nom'],
331
					'utilisateur[prenom]' => $infos_utilisateur['prenom'],
332
					'origin' => 'pullPlantnet',
333
				];
334
 
335
				foreach ($images as $i => $image) {
336
					$infos_obs["obsId1[image_nom][$i]"] = $image;
337
				}
3761 killian 338
				// var_dump($infos_obs);
3755 killian 339
 
340
				// curl post $infos_obs
341
				$ch = curl_init($url_cel_widget_saisie);
342
				curl_setopt($ch, CURLOPT_POST, true);
343
				curl_setopt($ch, CURLOPT_POSTFIELDS, $infos_obs);
344
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
345
				$reponse = curl_exec($ch);
346
				$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
347
				curl_close($ch);
348
 
349
				if (!$reponse || 200 != $code) {
350
					throw new Exception("Ça a pété à l'envoi de l'obs :\n $reponse\n avec l'obs : " . json_encode($infos_obs) . "\n");
351
				}
352
 
353
				// var_dump($reponse);
3761 killian 354
				$id_obs_tb = json_decode($reponse, true)['id'];
355
				$id_obs_pn = $obs['id'];
3755 killian 356
				// on insère les ids de correspondance obsPN obsTB dans la table cel_plantnet
357
				$sql = 'INSERT INTO cel_plantnet (id_observation, id_plantnet, date_maj)'
358
						.' VALUES (%s, %s, NOW())'
359
						. ' -- ' . __FILE__ . ':' . __LINE__;
3761 killian 360
				$sql = sprintf($sql, $this->bdd->proteger($id_obs_tb), $this->bdd->proteger($id_obs_pn));
3755 killian 361
				$this->bdd->requeter($sql);
3761 killian 362
 
363
				echo "Obs insérée en base : ID PN $id_obs_pn ; ID TB $id_obs_tb ; utilisateur_tb $email\n";
3755 killian 364
			}
365
		}
366
	}
367
 
368
	/**
369
	 * Return TB taxo repos names for given PN project
370
	 *
371
	 * @return string
372
	 */
373
	private function findProbableTaxoRepos($pnProjectId) {
374
		$selectedRepos = [];
375
		// Référentiels tela botanica indexés par référentiels PN (version octobre 2019)
376
		// @TODO à revoir en fonction des nouvelles mises en prod de nouveaux référentiels
377
		$tbTaxoRepos = [
378
			'afn' => [/*'apd', */'isfan'],
379
			'aft' => ['apd'],
380
			'antilles' => ['bdtxa', 'taxref'],
381
			'canada' => ['vascan'],
382
			'comores' => ['apd'],
383
			'endemia' => ['florical', 'taxref'],
384
			'taxref	' => ['bdtfx'],
385
			'guyane' => ['aublet', 'taxref'],
386
			'hawai' => [],
387
			'lapaz' => ['aublet', 'taxref'],
388
			'martinique' => ['bdtxa', 'taxref'],
389
			'maurice' => ['apd'],
390
			'medor' => ['lbf'],
391
			'namerica' => [],
392
			'polynesiefr' => ['taxref'],
393
			'prosea' => ['asia'],
394
			'prota' => ['isfan', 'apd'],
395
			'provence' => ['bdtfx', 'taxref'],
396
			'reunion' => ['bdtre', 'taxref'],
397
			'salad' => ['bdtfx', 'taxref'],
398
			'useful' => [],
399
			'weurope' => ['bdtfx'],
400
			'the-plant-list' => [],
401
			'iscantree' => ['apd'],
402
			'central-america' => [],
403
			'invasion' => ['bdtfx'],
404
			'weeds' => ['bdtfx'],
405
			'malaysia' => [],
406
		];
407
 
408
		if (array_key_exists($pnProjectId, $tbTaxoRepos)) {
409
			array_map(function($repo) use ($selectedRepos) {
410
				$selectedRepos[] = $repo;
411
			}, $tbTaxoRepos[$pnProjectId]);
412
		}
413
 
414
		// @TODO chercher le nom dans plusieurs référentiels avant d'envoyer l'obs
415
		// prendre "enrichirDonneesTaxonomiques" du service de saisie et le coller ici
416
		// en attendant on envoi juste le premier référentiel trouvé
417
		return $selectedRepos[0] ?? '';
418
	}
419
 
420
	/*
421
	 * Retrouve les infos d'un utilisateur tela à partir de son email
422
	 * @param string $email User email
423
	 * @return mixed 		Tableau des infos de l'utilisateur
424
	 *						False si l'email n'est pas trouvé dans l'annuaire
425
	 */
426
	private function findUserInfo($email) {
427
		// cherche dans le cache
428
		if (array_key_exists($email, $this->userInfos)) {
429
			$infosUtilisateur = $this->userInfos[$email];
430
			// echo("Email in cache : $email\n");
431
		} else {
432
			$infosUtilisateur = false;
433
			$urlInfosUtilisateur = str_replace('{email}', $email, Config::get('urlAnnuaireIdParEmail'));
434
 
435
			$ch = curl_init($urlInfosUtilisateur);
436
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
437
			$reponse = curl_exec($ch);
438
			$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
439
			curl_close($ch);
440
 
441
			// on peut pas tester le code de réponse de cette api, si l'utilisateur n'est pas trouvé ça fait une 500 >_<
442
			// une bonne réponse ressemble à ça :
443
			// {"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"}}
444
			$reponse = json_decode($reponse, true);
445
			if (!isset($reponse)) {
446
				throw new Exception("\nL'annuaire n'a pas répondu avec du json : code $code à l'adresse $urlInfosUtilisateur : $reponse\n");
447
			}
448
 
449
			if (!isset($reponse['error'])) {
450
				$infosUtilisateur = array_shift($reponse);
451
			}
452
 
453
			// met en cache
454
			$this->userInfos[$email] = $infosUtilisateur;
455
			// echo("Email cached : $email\n");
456
		}
457
 
458
		return $infosUtilisateur;
459
	}
460
 
3761 killian 461
	private function getGeoInfo($obs) {
462
		$geo = [];
463
		if (!isset($obs['lat']) && !isset($obs['lon'])) {
464
			return $geo;
465
		}
466
 
467
		// $data = [
468
		// 	'hitsPerPage' => 1,
469
		// 	'aroundLatLng' => "{$obs['lat']},{$obs['lon']}"
470
		// ];
471
		$headers = [
472
			'X-Algolia-Application-Id' => Config::get('algoliaApplicationId'),
473
			'X-Algolia-API-Key' => Config::get('algoliaAPIKey'),
474
		];
475
 
476
		$lat = number_format($obs['lat'], 6, '.', '');
477
		$lon = number_format($obs['lon'], 6, '.', '');
478
 
479
		$ch = curl_init(Config::get('urlReverseGeocodingLatLng')."$lat,$lon");
480
		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
481
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
482
		$reponse = curl_exec($ch);
483
		$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
484
		curl_close($ch);
485
 
486
		if ($reponse) {
487
			$reponse = json_decode($reponse, true);
488
			// die(var_dump($reponse));
489
			$infos = $reponse['hits'][0];
490
 
491
			$geo = [
492
				'lat' => (string) $obs['lat'],
493
				'lon' => (string) $obs['lon'],
494
				'country' => $infos['country']['fr'] ?? $infos['country']['default'],
495
				'city' => $infos['city']['default'][0] ?? null,
496
				'postcode' => $infos['postcode'][0] ?? null,
497
				'countryCode' => strtoupper($infos['country_code']),
498
			];
499
		}
500
 
501
		return $geo;
502
	}
503
 
3755 killian 504
	private function updateFromPN(array $pnObs, string $tbObsId) {
505
		if (!is_array($pnObs) || !is_string($tbObsId)) {
506
			// die(var_dump($pnObs, $tbObsId));
3761 killian 507
			throw new Exception("\nBad params types, give me an array and an integer plz\n");
3755 killian 508
		}
509
		// die(var_dump($pnObs));
510
 
3761 killian 511
		// log update date to cel_plantnet
512
		$sql = "UPDATE cel_plantnet SET date_maj = NOW() WHERE id_observation = $tbObsId"
513
				. ' -- ' . __FILE__ . ':' . __LINE__;
514
		$this->bdd->requeter($sql);
515
 
3755 killian 516
		// check for deleted
517
		if (isset($pnObs['deleted']) && (true === $pnObs['deleted'])) {
518
			// est-ce une obs issue de PN ?
519
			//// faut regarder le champ input_source == PlantNet
520
			$sql = "SELECT input_source FROM occurrence WHERE id = '$tbObsId'"
521
					. ' -- ' . __FILE__ . ':' . __LINE__;
522
			$res = $this->bdd->recupererTous($sql);
3761 killian 523
 
3755 killian 524
			if (isset($res[0]) && ('PlantNet' === $res[0]['input_source'])) {
525
				// oui ? alors supprimer obs !
3761 killian 526
				echo "Obs supprimée coté PN, suppression : ID PN {$obs['id']} ; ID TB {$res[0]['id_observation']}\n";
527
 
528
				$sql = "UPDATE photos SET occurrence_id = NULL WHERE occurrence_id = '$tbObsId'"
3755 killian 529
						. ' -- ' . __FILE__ . ':' . __LINE__;
530
				$this->bdd->requeter($sql);
3761 killian 531
 
532
				$sql = "DELETE FROM occurrence WHERE id = '$tbObsId'"
3755 killian 533
						. ' -- ' . __FILE__ . ':' . __LINE__;
534
				$this->bdd->requeter($sql);
535
			}
536
		}
537
 
538
		// check for deleted images
539
		foreach ($pnObs['images'] as $image) {
540
			if ($image['deleted']) {
541
				// no idea
542
				// y'a pas encore de lien tangible entre les images PN et les notres
543
			}
544
		}
545
 
546
		// @TODO : finir la comparaison des proposition entre celles de Tela et celles PN
547
		// // check for votes (notes et taxon)
548
		// $names = [];
549
		// foreach ($pnObs['computed']['votes'] as $vote) {
550
		// 	echo($vote['name']);
551
		// 	echo($vote['score']['pn']);
552
		// 	echo($vote['score']['total']);
553
 
554
		// 	$names[$vote['score']['pn']] = $vote['name'];
555
		// }
556
		// ksort($names, SORT_NUMERIC); // votes sorted by score asc
557
		// $pn_sorted_votes = array_reverse($names, true); // desc
558
 
559
		// // get existing votes
560
		// $sql = "SELECT id_commentaire, nom_sel, nom_sel_nn, nom_referentiel, nom_referentiel, utilisateur_courriel, proposition_initiale, proposition_retenue"
561
		// 		. "WHERE ce_observation = '$tbObsId' AND ce_commentaire_parent = 0"
562
		// 		. ' -- ' . __FILE__ . ':' . __LINE__;
563
		// $existing_votes = $this->bdd->recupererTous($sql);
564
 
565
		// // @TODO : compare votes
566
		// // insert_new_votes($pn_sorted_votes, $existing_votes);
567
	}
568
 
3761 killian 569
	private function updateOnePN($pnObsId, $pnProjectId) {
570
		if (!is_int($pnObsId) || !is_string($pnProjectId)) {
571
			die(var_dump($pnObsId, $pnProjectId));
572
			throw new Exception("\nBad params types, give me an integer and a string plz\n");
3755 killian 573
		}
3761 killian 574
		// get PN project list
575
		$list = [];
576
		$pnProjects = $this->getProjects(); // refresh projects list
577
		foreach ($pnProjects as $project) {
578
			$list[$project['id']] = $project['name'];
579
		}
3755 killian 580
 
3761 killian 581
		// if project not in list display list
582
		if (!array_key_exists($pnProjectId, $list)) {
583
			echo "Available projects:\n";
584
			foreach ($list as $projectId => $projectName) {
585
				echo " - $projectId ($projectName)\n";
586
			}
587
			throw new Exception("Project $pnProjectId does not exist\n");
588
		} else {
589
			$this->currentProject = [
590
				'id' => $pnProjectId,
591
				'name' => $list[$pnProjectId],
592
			];
593
		}
594
 
595
		// get PN obs
3755 killian 596
		$urlInfosObs = str_replace(
3761 killian 597
			['{token}', '{project}', '{id}'],
598
			[Config::get('tokenPlantnet'), $pnProjectId, $pnObsId],
3755 killian 599
			Config::get('urlPlantnetBase').Config::get('urlPlantnetObsById')
600
		);
601
		$ch = curl_init($urlInfosObs);
602
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
3761 killian 603
		$response = curl_exec($ch);
3755 killian 604
		$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
605
		curl_close($ch);
606
 
3761 killian 607
		if (!$response || 200 != $code) {
608
			throw new Exception("\nPlantnet api ($urlInfosObs) replied with code $code : $response\n");
3755 killian 609
		}
610
 
3761 killian 611
		// change last modification date to force update
612
		$obs = json_decode($response, true);
613
		$date = new DateTime();
614
		$date->setTimestamp(intdiv($obs['dateUpdated'], 1000) - 1);
615
		$date = $this->bdd->proteger($date->format('Y-m-d H:i:s'));
616
		$sql = "UPDATE cel_plantnet SET date_maj = $date WHERE id_plantnet = '$pnObsId'"
617
				. ' -- ' . __FILE__ . ':' . __LINE__;
618
		$this->bdd->requeter($sql);
619
 
620
		$this->updateObs([$obs]);
3755 killian 621
	}
622
 
623
	private function updateOneTB($id) {
624
		$corres = $this->findMatchingPartnerId($id, 'tb');
625
		echo "L'obs tela avec l'id $id a été trouvée chez plantnet avec l'id : " .$corres['pn'] . "\n";
626
		echo "La suite n'a pas été implémentée.\n";
627
	}
628
 
629
	/*
630
	 * Trouve les ids d'une obs chez les partenaires
631
	 * Il faut lancer updateMatchingPartnersIds pour obtenir une liste fraiche
632
	 *
633
	 * @param 	string $id			L'id de l'obs
634
	 * @param 	string $partner		Le partenaire correspondant à l'id de l'obs
635
	 *
636
	 * @return  mixed 				Le tableau de correspondances d'ids
637
	 *								False si l'id n'est pas trouvé
638
	 */
639
	private function findMatchingPartnerId($id, $partner) {
640
		if (!in_array($partner, $this->allowedPartners)) {
641
			throw new Exception("\nUnknown partner : $partner. Available Partners : " . implode(', ', $this->allowedPartners) . "\n");
642
		}
643
 
644
		// le json ressemble à ça :
645
		// {"tb":"2369732","pn":"1001020199"}, {"tb":"2369733","pn":"1001020176"}, ...
646
		$ids = json_decode(file_get_contents($this->correspondingIdsFilename), true);
647
		// extrait la colonne du partenaire recherché du tableau multidimensionnel fraichement décodé
648
		$partnerColumn = array_column($ids, $partner);
649
		// cherche l'index de l'id recherché
650
		$index = array_search($id, $partnerColumn);
651
 
652
		return $index ? $ids[$index] : false;
653
	}
654
 
655
	private function updateCorrespondingIdsTable() {
656
		// first update cache file if necessary
657
		if (!file_exists($this->correspondingIdsFilename) || time() > (filemtime($this->correspondingIdsFilename) + (24 * 3600))) {
658
			$this->updateMatchingPartnersIds();
659
		}
660
 
661
		$data = file_get_contents($this->correspondingIdsFilename);
662
		$data = json_decode($data, true);
663
 
664
		$now = new DateTime;
665
		$now = $this->bdd->proteger($now->format('Y-m-d H:i:s'));
666
 
667
		$sqlInsert = 'INSERT INTO cel_plantnet (id_observation, id_plantnet, date_maj)'
668
					. ' VALUES %s'
669
					. ' ON DUPLICATE KEY UPDATE id_observation=VALUES(id_observation), id_plantnet=VALUES(id_plantnet)'
670
					. ' -- ' . __FILE__ . ':' . __LINE__;
671
		$values = '';
672
 
3761 killian 673
		echo "Updating matching partners ids table\n";
3755 killian 674
		foreach ($data as $id => $corres) {
675
			$id_obs_tb = $this->bdd->proteger($corres['tb']);
676
			$id_obs_pn = $this->bdd->proteger($corres['pn']);
677
			// on insère les ids de correspondance obsPN obsTB dans la table cel_plantnet
678
			$values .= " ($id_obs_tb, $id_obs_pn, $now),";
679
 
680
			if (0 === $id % 100) {
681
				$values = substr($values, 0, -1); // retire la dernière virgule
682
				$sql = sprintf($sqlInsert, $values);
683
				// var_dump($sql);
684
				$this->bdd->requeter($sql);
685
				$values = '';
686
			}
687
		}
688
		// Faut envoyer les dernières données qui sont pas passées dans le modulo
689
		$values = substr($values, 0, -1); // retire la dernière virgule
690
		$sql = sprintf($sqlInsert, $values);
691
		// var_dump($sql);
692
		$this->bdd->requeter($sql);
693
 
3761 killian 694
		$count = count($data);
695
		echo "Success: #$count updated\n";
3755 killian 696
	}
697
 
698
	private function updateMatchingPartnersIds() {
699
		// curl -X GET --header 'Accept: application/json' 'https://bourbonnais.cirad.fr:8081/v1/edi/observations/partnerids?token=f0ca433febe320675c24ee2ddfab8b82f65d556b' > partnerids.txt
700
		$matchingPartnersIdsServiceUrl = str_replace(
701
			'{token}',
702
			Config::get('tokenPlantnet'),
703
			Config::get('urlPlantnetBase').Config::get('urlPlantnetMatchingPartner')
704
		);
705
		$ch = curl_init($matchingPartnersIdsServiceUrl);
706
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
707
 
708
		echo "Updating matching partners ids...\n";
709
		$reponse = curl_exec($ch);
710
		$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
711
		curl_close($ch);
712
 
713
 
714
		if (!$reponse || 200 != $code) {
715
			throw new Exception("\nError updating partners ids, http error code \"$code\" whith url \"$matchingPartnersIdsServiceUrl\"...\n");
716
		}
717
		echo "Response data from PN api gathered, know computing...\n";
718
 
719
		if (!file_put_contents($this->correspondingIdsFilename, $reponse)) {
720
			throw new Exception("\nError writing correspondingIdsFilename with path : " . $this->correspondingIdsFilename . "\n");
721
		}
722
		echo "Matching partners ids saved!";
723
	}
724
}