Subversion Repositories eFlore/Applications.coel

Rev

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