Subversion Repositories eFlore/Applications.coel

Rev

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