Subversion Repositories eFlore/Applications.coel

Rev

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