Subversion Repositories eFlore/Applications.coel

Rev

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