Subversion Repositories eFlore/Applications.cel

Rev

Rev 3785 | Only display areas with differences | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

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