Subversion Repositories eFlore/Applications.coel

Rev

Rev 1649 | Rev 1669 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
1497 jpm 1
<?php
2
/**
3
 * Service fournissant la liste des structures et leurs informations.
4
 * Encodage en entrée : utf8
5
 * Encodage en sortie : utf8
6
 *
7
 * @author Jean-Pascal MILCENT <jpm@tela-botanica.org>
8
 * @license GPL v3 <http://www.gnu.org/licenses/gpl.txt>
9
 * @license CECILL v2 <http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt>
10
 * @version $Id$
11
 * @copyright 2009
12
 */
13
class CoelStructure extends Coel {
14
 
15
	// ATTENTION : tjrs garder la table principale en premier, puis mettre les tables spécialisées.
16
	protected $tables = array(	120 => array(
17
									'nom' => 'coel_structure',
18
									'prefixe' => 'cs',
19
									'id' => array('cs_id_structure')),
20
		   						122 => array(
21
		   							'nom' => 'coel_structure_conservation',
22
		   							'prefixe' => 'csc',
23
		   							'id' => array('csc_id_structure')),
24
		   						123 => array(
25
		   							'nom' => 'coel_structure_valorisation',
26
		   							'prefixe' => 'csv',
27
		   							'id' => array('csv_id_structure')));
28
 
29
	/**
30
	 * Méthode principale appelée avec une requête de type GET.
31
	 */
32
	public function getElement($param = array()) {
33
		// Initialisation des variables
34
		$info = array();
35
 
36
		// Nour recherchons le type de requête demandé
37
		$type = $param[0];
38
 
39
		if ($type == '*' || is_numeric($type)) {
40
			$info = $this->getElementParDefaut($param);
41
		} else {
42
			$methode = 'getElement'.$type;
43
			if (method_exists($this, $methode)) {
44
				array_shift($param);
45
				$info = $this->$methode($param);
46
			} else {
47
				$this->messages[] = "Le type d'information demandé '$type' n'est pas disponible.";
48
			}
49
		}
50
 
51
		// Envoie sur la sortie standard
52
		$this->envoyer($info);
53
	}
54
 
55
	/**
56
	 * Méthode par défaut pour garder la compatibilité avec Coel.
57
	 * Appelée avec les paramêtres d'url suivant :
58
	 * /CoelStructure/_/_/_
59
	 * ou les _ représentent dans l'ordre : id_projet, id_structure et nom
60
	 * Si un des paramêtres est abscent, il prendre la valeur *
61
	 */
62
	public function getElementParDefaut($param) {
63
		// Initialisation des variables
64
		$info = array();
65
 
66
		// Pré traitement des paramêtres
1636 aurelien 67
		$p = $this->traiterParametresUrl(array('id_projet', 'id_structure', 'recherche'), $param);
1497 jpm 68
 
69
		// Construction de la requête
70
		$requete = 	(($this->distinct) ? 'SELECT DISTINCT' : 'SELECT').' cs.*, csc.*, csv.*, '.
71
					'	cmhl_date_modification, cmhl_notes, cmhl_source, cmhl_ce_modifier_par, cmhl_ce_etat, cmhl_ip '.
72
					'FROM coel_structure AS cs '.
73
					'	LEFT JOIN coel_meta_historique_ligne ON (cs_ce_meta = cmhl_id_historique_ligne) '.
74
					'	LEFT JOIN coel_structure_conservation AS csc ON (cs_id_structure = csc_id_structure) '.
75
					'	LEFT JOIN coel_structure_valorisation AS csv ON (cs_id_structure = csv_id_structure) '.
76
					((count($p) != 0) ? 'WHERE ' : '').
77
					((isset($p['id_projet'])) ? "AND cs_ce_projet = {$p['id_projet']} " : '').
78
					((isset($p['id_structure'])) ? "AND cs_id_structure = {$p['id_structure']} " : '').
1636 aurelien 79
					(isset($p['recherche']) ? $this->construireWhereRecherche($p['recherche']) : '').
1497 jpm 80
					'ORDER BY '.((!is_null($this->orderby)) ? $this->orderby  : 'cs.cs_nom ASC').' ';
81
 
82
		$requete = str_replace('WHERE AND', 'WHERE', $requete);
83
		$requete_compte = $requete;
84
		$requete .= "LIMIT $this->start, $this->limit ";
85
 
86
		// Récupération des résultats
87
		try {
88
			// SPÉCIAL :
89
			// Lorsqu'on cherche une seule structure avec un id passé en paramêtre, nous devons renvoyer un objet
1595 aurelien 90
			$donnees = ($this->formatRetour == 'objet' && isset($p['id_structure'])) ? $this->bdd->query($requete)->fetch(PDO::FETCH_OBJ) : $this->bdd->query($requete)->fetchAll(PDO::FETCH_ASSOC);
1497 jpm 91
			if ($donnees === false) {
92
				$this->messages[] = "La requête a retourné aucun résultat.";
93
			}
94
 
95
			$elements_nbre = $this->bdd->query($requete_compte)->rowCount();
96
			$info['nbElements'] = $elements_nbre;
97
			$info['structures'] = $donnees;
98
		} catch (PDOException $e) {
99
			$this->messages[] = sprintf($this->getTxt('sql_erreur'), $e->getFile(), $e->getLine(), $e->getMessage());
100
		}
101
 
102
		return $info;
103
	}
104
 
1636 aurelien 105
	private function construireWhereRecherche($recherche) {
106
		$recherche = "AND ".
107
		"(".
108
			"cs_nom LIKE {$recherche}  OR ".
109
			"cs_ville LIKE {$recherche} ".
110
		")";
111
		return $recherche;
112
	}
113
 
1497 jpm 114
	/* Méthode pour récupérer le nombre de structure par zone géographique.
115
	 * Appelée avec les paramêtres d'url suivant :
116
	 * /CoelStructure/ParZoneGeo/_
117
	 * ou les _ représentent dans l'ordre : type.
118
	 * ou type peut valoir: FRD (= département français)
119
	 * Si un des paramêtres est abscent, il prendre la valeur *
120
	 */
121
	public function getElementParZoneGeo($param) {
122
		// Initialisation des variables
123
		$info = array();
124
 
125
		// Pré traitement des paramêtres
1581 jpm 126
		$p = $this->traiterParametresUrl(array('type', 'projets'), $param);
1497 jpm 127
		if (!isset($p['type'])) {
128
			$this->messages[] = "Il est obligatoire d'indiquer type de recherche pour utiliser ce service.";
129
		} else {
130
			// Construction de la requête
131
			$requete = 	(($this->distinct) ? 'SELECT DISTINCT' : 'SELECT').' '.
132
						'	IF ( SUBSTRING( cs_code_postal FROM 1 FOR 2 ) >= 96, '.
133
						'		SUBSTRING( cs_code_postal FROM 1 FOR 3 ), '.
134
						'		SUBSTRING( cs_code_postal FROM 1 FOR 2 ) ) AS id, '.
135
						'	COUNT( cs_id_structure ) AS nbre '.
136
						'FROM coel_structure '.
137
						'WHERE cs_ce_truk_pays = 2654 '.
1581 jpm 138
						(isset($p['projets']) ? "	AND cs_ce_projet IN ({$p['projets']}) " : '').
1497 jpm 139
						'GROUP BY IF ( SUBSTRING( cs_code_postal FROM 1 FOR 2 ) >= 96, '.
140
						'	SUBSTRING( cs_code_postal FROM 1 FOR 3 ), '.
141
						'	SUBSTRING( cs_code_postal FROM 1 FOR 2 ) ) '.
142
						'ORDER BY '.((!is_null($this->orderby)) ? $this->orderby  : 'id ASC').' ';
143
			// Récupération des résultats
144
			try {
145
				$donnees = $this->bdd->query($requete)->fetchAll(PDO::FETCH_ASSOC);
146
				if ($donnees === false) {
147
					$this->messages[] = "La requête a retourné aucun résultat.";
148
				} else {
149
					foreach ($donnees as $donnee) {
150
						$info[$donnee['id']] = $donnee['nbre'];
151
					}
152
				}
153
			} catch (PDOException $e) {
154
				$this->messages[] = sprintf($this->getTxt('sql_erreur'), $e->getFile(), $e->getLine(), $e->getMessage());
155
			}
156
		}
157
		return $info;
158
	}
159
 
160
	/**
161
	 * Méthode appelée pour ajouter un élément.
162
	 */
163
	public function createElement($params) {
164
		// Identification de l'utilisateur
165
		list($id_utilisateur, $id_session) = $this->getIdentification($params);
1648 raphael 166
 
1497 jpm 167
		// Contrôle du non détournement de l'utilisateur
1648 raphael 168
		if (!$this->etreAutorise($id_utilisateur)) {
169
			$this->envoyer();
170
			return;
171
		}
172
		try {
173
			// Vérification des tables à vraiment mettre à jour en fonction des données passées.
1649 raphael 174
			if( (! @$params['cs_latitude'] || ! @$params['cs_longitude']) &&
175
				(@$params['cs_adresse_01'] || @$params['cs_code_postal'] || @$params['cs_ville']) ) {
176
				$lonlat = array();
177
				if(Coel::coordGuess(Coel::addrReStruct($params), $lonlat)) {
178
					$params['cs_latitude'] = $lonlat['lat'];
179
					$params['cs_longitude'] = $lonlat['lon'];
180
				}
181
			}
182
 
1648 raphael 183
			$tables_a_modifier = $this->recupererTablesAModifier($params);
184
			reset($tables_a_modifier);
1649 raphael 185
 
1648 raphael 186
			$id_structure = null;
187
			while (list($table_id, $table) = each($tables_a_modifier)) {
188
				if (is_null($table['champs'])) continue;
189
				if ($this->avoirCleComplete($table)) {
190
					$this->mettreAJourAvecCle($id_utilisateur, $id_session, $table_id, $table);
191
					continue;
192
				}
193
 
194
				// Ajout des données à la table des données
195
				$id_structure = $this->ajouter($table);
196
				if ($id_structure === false) continue;
197
 
198
				$table['champs_valeurs_id']['cs_id_structure'] = $id_structure;
199
				$table['champs_valeurs_brut']['cs_id_structure'] = $id_structure;
200
				$tables_a_modifier[122]['champs_valeurs_id']['csc_id_structure'] = $id_structure;
201
				$tables_a_modifier[122]['champs_valeurs_brut']['csc_id_structure'] = $id_structure;
202
				$tables_a_modifier[122]['champs_valeurs_protege']['csc_id_structure'] = $this->bdd->quote($id_structure);
203
				$tables_a_modifier[123]['champs_valeurs_id']['csv_id_structure'] = $id_structure;
204
				$tables_a_modifier[123]['champs_valeurs_brut']['csv_id_structure'] = $id_structure;
205
				$tables_a_modifier[123]['champs_valeurs_protege']['csv_id_structure'] = $this->bdd->quote($id_structure);
1649 raphael 206
 
1648 raphael 207
				// Historisation (Ajout des méta-données)
208
				$etat = 1; // Ajout
209
				$cle = $this->recupererCle($table);
210
				$info = $this->creerXmlHisto($table['champs_valeurs_brut']);
211
				$id_meta = $this->historiser($table_id, $cle, $info, $id_utilisateur, $etat, $id_session);
1497 jpm 212
 
1648 raphael 213
				// Liaison de la table des données à ses méta-données
214
				$champ_meta = "{$table['prefixe']}_ce_meta";
215
				$table['champs_valeurs_protege'] = array($champ_meta => $id_meta);
216
				$this->modifier($table);
217
			}
218
 
219
			if(isset($params['cpr_abreviation']) && !empty($params['cpr_abreviation'])) {
1497 jpm 220
				$this->ajouterGuid($params['cpr_abreviation'], $id_structure);
221
			}
1648 raphael 222
		} catch (PDOException $e) {
223
			$this->messages[] = sprintf($this->getTxt('sql_erreur'), $e->getFile(), $e->getLine(), $e->getMessage(), $requete);
224
		}
1497 jpm 225
 
226
	   	$this->envoyer($id_structure);
227
	}
228
 
229
	/**
230
	 * Méthode appelée pour mettre à jour un élément
231
	 */
232
	public function updateElement($uid, $params) {
233
		// Vérification de la présence des id passés par l'url
234
		if (!isset($uid[0])) {
235
			$this->messages[] = "Identifiant de structure manquant. Vous ne devriez pas avoir accès à ce service.";
1648 raphael 236
			$this->envoyer();
237
			return;
238
		}
239
 
240
		// Identification de l'utilisateur
241
		list($id_utilisateur, $id_session) = $this->getIdentification($params);
242
		// Contrôle du non détournement de l'utilisateur
243
		if (!$this->etreAutorise($id_utilisateur)) {
244
			$this->envoyer();
245
			return;
246
		}
247
		try {
1651 raphael 248
			$form_needs_refresh = FALSE;
249
			if( (! @$params['cs_latitude'] || ! @$params['cs_longitude']) &&
250
				(@$params['cs_adresse_01'] || @$params['cs_code_postal'] || @$params['cs_ville']) ) {
251
				$lonlat = array();
252
				if(Coel::coordGuess(Coel::addrReStruct($params), $lonlat)) {
253
					$params['cs_latitude'] = $lonlat['lat'];
254
					$params['cs_longitude'] = $lonlat['lon'];
255
					$form_needs_refresh = TRUE;
256
				}
257
			}
258
 
1648 raphael 259
			// Vérification des tables à vraiment mettre à jour en fonction des données passées.
260
			$tables_a_modifier = $this->recupererTablesAModifier($params);
1497 jpm 261
 
1648 raphael 262
			// Pour chaque table du module nous lançons si nécessaire l'historisation puis la mise à jour
263
			foreach ($tables_a_modifier as $table_id => $table) {
264
				$this->mettreAJourAvecCle($id_utilisateur, $id_session, $table_id, $table);
265
			}
266
		} catch (PDOException $e) {
267
			$this->messages[] = sprintf($this->getTxt('sql_erreur'), $e->getFile(), $e->getLine(), $e->getMessage(), $requete);
1497 jpm 268
		}
1651 raphael 269
 
1497 jpm 270
		// Envoie sur la sortie standard
1651 raphael 271
 
272
		if($form_needs_refresh) { // coordonnées mises à jour en DB: en informer le formulaire (si resté ouvert)
273
			// $this->envoyer('reload'); // TODO: handle this
274
		}
275
		$this->envoyer(); // OK par défaut
1497 jpm 276
	}
277
 
278
	/**
279
	 * Méthode appelée pour supprimer un élément
280
	 */
281
	public function deleteElement($uid) {
282
	   	// NOTES : une structure ne peut pas être supprimée si elle possède des collections liées.
283
		// Vérification de la présence des id passés par l'url
284
		if (!isset($uid[0]) || !isset($uid[1])) {
285
				$this->messages[] = "Identifiant de structure ou d'utilisateur manquant. Vous ne devriez pas avoir accès à ce service.";
286
		} else {
287
			// Identification de l'utilisateur
288
			list($id_utilisateur, $id_session) = $this->getIdentification($uid[0]);
289
 
290
			// Contrôle du non détournement de l'utilisateur
291
			if ($this->etreAutorise($id_utilisateur)) {
292
				// Récupération des id passés par l'url
293
				$identifiants = explode(',', rtrim($uid[1], ','));
294
 
295
		   		try {
296
		   			if (count($identifiants) == 0) {
297
		   				$this->messages[] = "Aucun enregistrement n'a été supprimé.";
298
		   			} else {
299
			   			foreach ($identifiants as $id_structure) {
300
				   			// Vérification que la structure ne possède pas de collections liées
301
							if ($this->verifierPresenceCollection($id_structure) === false) {
302
								$params = array('cs_id_structure' => $id_structure, 'csc_id_structure' => $id_structure, 'csv_id_structure' => $id_structure);
303
								$tables_a_modifier = $this->recupererTablesAModifier($params);
304
 
305
								foreach ($tables_a_modifier as $table_id => $table) {
306
						   			if ($this->avoirEnregistrement($table)) {
307
						   				$resultat = $this->supprimer($table);
308
										if ($resultat === true) {
309
											// Historisation (Ajout des méta-données)
310
											$cle = $this->recupererCle($table);
311
											$this->historiser($table_id, $cle, 'NULL', $id_utilisateur, 3, $id_session);
312
										}
313
						   			}
314
					   			}
315
							} else {
316
								$this->messages[] = "La structure '$id_structure' ne peut pas être supprimée car elle possède des collections liées.";
317
							}
318
			   			}
319
		   			}
320
			   	} catch (PDOException $e) {
321
					$this->messages[] = sprintf($this->getTxt('sql_erreur'), $e->getFile(), $e->getLine(), $e->getMessage(), $requete);
322
				}
323
		   	}
324
		}
325
 
326
		// Envoie sur la sortie standard
327
		$this->envoyer();
328
	}
329
 
330
	private function verifierPresenceCollection($id_structure) {
331
		$requete = 	'SELECT COUNT(cc_id_collection) AS nbre_collection '.
332
					'FROM coel_collection '.
333
					"WHERE cc_ce_structure = '$id_structure' ".
334
	   				'GROUP BY cc_ce_structure ';
335
 
336
		// Vérification que la structure ne possède pas de collections liées
337
		$nbre_collection = $this->bdd->query($requete)->fetchColumn();
338
 
339
		$presence = false;
340
		if ($nbre_collection != 0) {
341
			$presence = true;
342
		}
343
		return $presence;
344
	}
345
 
346
	private function ajouterGuid($abr_projet, $id_structure) {
347
		if ($id_structure !== false) {
348
			$table_guid = $this->tables[120];
349
			$table_guid['champs_valeurs_id']['cs_id_structure'] = $id_structure;
350
			$table_guid['champs_valeurs_protege']['cs_guid'] = $this->bdd->quote(sprintf($this->config['coel']['guid'], $abr_projet, 'str'.$id_structure));
351
			$this->modifier($table_guid);
352
		}
353
	}
354
}
355
?>