Subversion Repositories eFlore/Applications.cel

Rev

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