Subversion Repositories eFlore/Applications.coel

Rev

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