Subversion Repositories eFlore/Applications.cel

Rev

Rev 1322 | Go to most recent revision | Only display areas with differences | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 1322 Rev 1327
1
<?php
1
<?php
2
// In : utf8
2
// In : utf8
3
// Out : utf8
3
// Out : utf8
4
 
4
 
5
// TODO : doublons
5
// TODO : doublons
6
 
6
 
7
/**
7
/**
8
Octobre 2010 David Delon.
8
Octobre 2010 David Delon.
9
Import d'observations dans le carnet en ligne à partir d'un fichier excel chargé par l'utilisateur
9
Import d'observations dans le carnet en ligne à partir d'un fichier excel chargé par l'utilisateur
10
et liaison d'images déjà chargee aux observations ainsi crées.
10
et liaison d'images déjà chargee aux observations ainsi crées.
11
 
11
 
12
Nom des colonnes imposé, mais présence de toutes les colonnes non obligatoires, ordre non imposé
12
Nom des colonnes imposé, mais présence de toutes les colonnes non obligatoires, ordre non imposé
13
Aucune valeur dans les colonnes n'est obligatoire
13
Aucune valeur dans les colonnes n'est obligatoire
14
Pour une ligne donnée, si tous les champs vides on ne fait rien, ou si seul le champ image est présent.
14
Pour une ligne donnée, si tous les champs vides on ne fait rien, ou si seul le champ image est présent.
15
Si la seule différence entre deux lignes est la valeur de la colonne image, on considère que c'est la même observation à laquelle on associe plusieurs images.
15
Si la seule différence entre deux lignes est la valeur de la colonne image, on considère que c'est la même observation à laquelle on associe plusieurs images.
16
Si au moins deux lignes (ou plus) sont complètement identiques on prend en compte une seule ligne (les doublons sont éliminés).
16
Si au moins deux lignes (ou plus) sont complètement identiques on prend en compte une seule ligne (les doublons sont éliminés).
17
**/
17
**/
18
 
18
 
19
// Nom des colonnes
19
// Nom des colonnes
20
 
20
 
21
define('COMMUNE','commune'); // soit un nom de commune, soit un code INSEE (5 chiffres), ou "nom de commune (numero departement)"
21
define('COMMUNE','commune'); // soit un nom de commune, soit un code INSEE (5 chiffres), ou "nom de commune (numero departement)"
22
define('LIEUDIT','lieu-dit'); // Texte libre
22
define('LIEUDIT','lieu-dit'); // Texte libre
23
define('STATION','station'); // Texte libre
23
define('STATION','station'); // Texte libre
24
define('MILIEU','milieu'); // Texte libre
24
define('MILIEU','milieu'); // Texte libre
25
define('LATITUDE','latitude'); // En decimal systeme WGS84
25
define('LATITUDE','latitude'); // En decimal systeme WGS84
26
define('LONGITUDE','longitude'); // En decimal systeme WGS84 
26
define('LONGITUDE','longitude'); // En decimal systeme WGS84 
27
define('NOTES','notes'); // Texte libre
27
define('NOTES','notes'); // Texte libre
28
define('DATEOBS','date'); // date au format jj/mm/aaaa
28
define('DATEOBS','date'); // date au format jj/mm/aaaa
29
define('ESPECE','espece'); // texte libre, nom latin, ou code nomenclatural (format BDNFFnn999999)
29
define('ESPECE','espece'); // texte libre, nom latin, ou code nomenclatural (format BDNFFnn999999)
30
define('IMAGE','image'); //  nom des fichiers images préalablement uploadés sur le CEL séparés par des "/"
30
define('IMAGE','image'); //  nom des fichiers images préalablement uploadés sur le CEL séparés par des "/"
31
define('DEPARTEMENT','departement'); //  Texte libre
31
define('DEPARTEMENT','departement'); //  Texte libre
32
define('TRANSMETTRE','transmettre'); //  "1" ou "oui", toute autre valeur (y compris vide) sera consideree comme "non""
32
define('TRANSMETTRE','transmettre'); //  "1" ou "oui", toute autre valeur (y compris vide) sera consideree comme "non""
33
 
33
 
34
 
34
 
35
// Resultat de l'analyse d'une ligne
35
// Resultat de l'analyse d'une ligne
36
define('LIGNE_VIDE',1); //  
36
define('LIGNE_VIDE',1); //  
37
define('LIGNE_NORMALE',2); //  
37
define('LIGNE_NORMALE',2); //  
38
define('LIGNE_IMAGE_SEULEMENT',3); //  
38
define('LIGNE_IMAGE_SEULEMENT',3); //  
39
 
39
 
40
 
40
 
41
//TODO: refactoriser entièrement cette classe
41
//TODO: refactoriser entièrement cette classe
42
class InventoryImportExcel extends Cel  {
42
class InventoryImportExcel extends Cel  {
43
 
43
 
44
	// Element constituant une observation 
44
	// Element constituant une observation 
45
	var $format_observation=array(COMMUNE ,LIEUDIT ,STATION , DEPARTEMENT, MILIEU ,LATITUDE ,LONGITUDE ,NOTES ,DATEOBS ,ESPECE ,TRANSMETTRE, IMAGE );
45
	var $format_observation=array(COMMUNE ,LIEUDIT ,STATION , DEPARTEMENT, MILIEU ,LATITUDE ,LONGITUDE ,NOTES ,DATEOBS ,ESPECE ,TRANSMETTRE, IMAGE );
46
 
46
 
47
	// Encapsulation classe lecture fichier excel
47
	// Encapsulation classe lecture fichier excel
48
	var $extendExcelReader;
48
	var $extendExcelReader;
49
 
49
 
50
	// Dernier numero d'ordre utilise
50
	// Dernier numero d'ordre utilise
51
	var $dernier_ordre = 1;
51
	var $dernier_ordre = 1;
52
	
52
	
53
	var $cpt_images_liees = 0;
53
	var $cpt_images_liees = 0;
54
 
54
 
55
	/**
55
	/**
56
	 Constructeur
56
	 Constructeur
57
	**/
57
	**/
58
	function InventoryImportExcel($config) {
58
	function InventoryImportExcel($config) {
59
 
59
 
60
		parent::__construct($config);	
60
		parent::__construct($config);	
61
		// Pas d'heritage multiple en php :(
61
		// Pas d'heritage multiple en php :(
62
		$this->extendExcelReader = new ExcelReader();
62
		$this->extendExcelReader = new ExcelReader();
63
		$this->extendExcelReader->initExcelReader();
63
		$this->extendExcelReader->initExcelReader();
64
	}
64
	}
65
 
65
 
66
	/**
66
	/**
67
	 Sur post
67
	 Sur post
68
	**/
68
	**/
69
	function createElement($pairs) {
69
	function createElement($pairs) {
70
 
70
 
71
		if(!isset($pairs['utilisateur']) || trim($pairs['utilisateur']) == '') {
71
		if(!isset($pairs['utilisateur']) || trim($pairs['utilisateur']) == '') {
72
			echo '0'; exit;
72
			echo '0'; exit;
73
		}
73
		}
74
		
74
		
75
		if(!isset($_SESSION)) {session_start();}
75
		if(!isset($_SESSION)) {session_start();}
76
        $this->controleUtilisateur($pairs['utilisateur']);
76
        $this->controleUtilisateur($pairs['utilisateur']);
77
 
77
 
78
        foreach($_FILES as $file) { // C'est le plus simple
78
        foreach($_FILES as $file) { // C'est le plus simple
79
            $infos_fichier = $file ;
79
            $infos_fichier = $file ;
80
        }
80
        }
81
 
81
 
82
		// Chargement tableau en memoire
82
		// Chargement tableau en memoire
83
		$data = new Spreadsheet_Excel_Reader($infos_fichier['tmp_name'], false); // false : pour menager la memoire.
83
		$data = new Spreadsheet_Excel_Reader($infos_fichier['tmp_name'], false); // false : pour menager la memoire.
84
		$arr = array();
84
		$arr = array();
85
 
85
 
86
		$rowcount=$data->rowcount(0);
86
		$rowcount=$data->rowcount(0);
87
		$colcount=$data->colcount(0);
87
		$colcount=$data->colcount(0);
88
 
88
 
89
		if ($rowcount<=1) { // TODO : retour erreur
89
		if ($rowcount<=1) { // TODO : retour erreur
90
			print "Tableau vide";
90
			print "Tableau vide";
91
			exit;
91
			exit;
92
		}
92
		}
93
 
93
 
94
		// Chargement tableau 
94
		// Chargement tableau 
95
        for($row=1;$row<=$rowcount;$row++) 
95
        for($row=1;$row<=$rowcount;$row++) 
96
            for($col=1;$col<=$colcount;$col++) 
96
            for($col=1;$col<=$colcount;$col++) 
97
                $arr[$col][$row] = $data->val($row,$col,0); // Attention, inversion voulue
97
                $arr[$col][$row] = $data->val($row,$col,0); // Attention, inversion voulue
98
              
98
              
99
		// 1 : Traitement intitules
99
		// 1 : Traitement intitules
100
		$line = array();
100
		$line = array();
101
 
101
 
102
		/* Les colonnes ne sont pas forcemment dans l'ordre  : on les extrait pour traitement futur  */	
102
		/* Les colonnes ne sont pas forcemment dans l'ordre  : on les extrait pour traitement futur  */	
103
        for($col=1;$col<=$colcount;$col++) {
103
        for($col=1;$col<=$colcount;$col++) {
104
            $colonne=strtolower($arr[$col][1]);
104
            $colonne=strtolower($arr[$col][1]);
105
            $colonne=trim($colonne);
105
            $colonne=trim($colonne);
106
            $colonne=cp1252_to_utf8($colonne);
106
            $colonne=cp1252_to_utf8($colonne);
107
            $colonne=remove_accent($colonne);
107
            $colonne=remove_accent($colonne);
108
            switch ($colonne) {  // On ne garde que les colonnes que l'on souhaite traiter
108
            switch ($colonne) {  // On ne garde que les colonnes que l'on souhaite traiter
109
                case COMMUNE:
109
                case COMMUNE:
110
                case LIEUDIT:
110
                case LIEUDIT:
111
                case STATION:
111
                case STATION:
112
                case MILIEU:
112
                case MILIEU:
113
                case DEPARTEMENT:
113
                case DEPARTEMENT:
114
                case LATITUDE:
114
                case LATITUDE:
115
                case LONGITUDE:
115
                case LONGITUDE:
116
                case NOTES:
116
                case NOTES:
117
                case DATEOBS:
117
                case DATEOBS:
118
                case ESPECE:
118
                case ESPECE:
119
                case TRANSMETTRE:
119
                case TRANSMETTRE:
120
                case IMAGE:
120
                case IMAGE:
121
                    $selection=array_values($arr[$col]);
121
                    $selection=array_values($arr[$col]);
122
                    array_shift($selection); // On ne garde pas la premiere ligne, qui contient les intitules
122
                    array_shift($selection); // On ne garde pas la premiere ligne, qui contient les intitules
123
                    $line[$colonne]=$selection;
123
                    $line[$colonne]=$selection;
124
                    break;
124
                    break;
125
 
125
 
126
            }
126
            }
127
        } 
127
        } 
128
		// 1 : Traitement lignes
128
		// 1 : Traitement lignes
129
		$cpt_obs=0;
129
		$cpt_obs=0;
130
		$cpt_img=0;
130
		$cpt_img=0;
131
 
131
 
132
        /* Recherche dernier numero d'ordre utilise : pas de mise a jour concurente a priori */
132
        /* Recherche dernier numero d'ordre utilise : pas de mise a jour concurente a priori */
133
        $requete = "SELECT MAX(ordre) AS ordre FROM cel_obs WHERE ce_utilisateur = ".$this->proteger($pairs['utilisateur'])." ";
133
        $requete = "SELECT MAX(ordre) AS ordre FROM cel_obs WHERE ce_utilisateur = ".$this->proteger($pairs['utilisateur'])." ";
134
		$resultat = $this->requeter($requete);
134
		$resultat = $this->requeter($requete);
135
 
135
 
136
        if(is_array($resultat) && count($resultat) > 0) {
136
        if(is_array($resultat) && count($resultat) > 0) {
137
            $this->dernier_ordre = $resultat[0]['ordre']; // 1  par defaut
137
            $this->dernier_ordre = $resultat[0]['ordre']; // 1  par defaut
138
        }
138
        }
139
 
139
 
140
		for ($i=0;$i<=$rowcount-1;$i++) {
140
		for ($i=0;$i<=$rowcount-1;$i++) {
141
			// On saute les eventuelles lignes vides du debut et les lignes contenant des information sur image uniquement
141
			// On saute les eventuelles lignes vides du debut et les lignes contenant des information sur image uniquement
142
			while ((in_array($retour_analyse=$this->analyserLigne($line,$i),array(LIGNE_IMAGE_SEULEMENT, LIGNE_VIDE))) && ($i<=$rowcount)) {
142
			while ((in_array($retour_analyse=$this->analyserLigne($line,$i),array(LIGNE_IMAGE_SEULEMENT, LIGNE_VIDE))) && ($i<=$rowcount)) {
143
				if  ($retour_analyse==LIGNE_IMAGE_SEULEMENT) {
143
				if  ($retour_analyse==LIGNE_IMAGE_SEULEMENT) {
144
					// image non rattachée à une observation
144
					// image non rattachée à une observation
145
				}
145
				}
146
				else {
146
				else {
147
					// ligne vide
147
					// ligne vide
148
				}
148
				}
149
				$i++;
149
				$i++;
150
			}
150
			}
151
			while (($this->analyserLigne($line,$i)==LIGNE_NORMALE) && ($i<=$rowcount)) {
151
			while (($this->analyserLigne($line,$i)==LIGNE_NORMALE) && ($i<=$rowcount)) {
152
				$id_obs = $this->traiterLigne($line,$i,$pairs['utilisateur']);
152
				$id_obs = $this->traiterLigne($line,$i,$pairs['utilisateur']);
153
				if ($this->dernier_ordre > 0) {
153
				if ($this->dernier_ordre > 0) {
154
					$cpt_obs++; // Compteur d'observations crees
154
					$cpt_obs++; // Compteur d'observations crees
155
				}
155
				}
156
				$i++;
156
				$i++;
157
				// On saute les lignes vide ou on traite les lignes suivantes contenant des informations sur image seulement
157
				// On saute les lignes vide ou on traite les lignes suivantes contenant des informations sur image seulement
158
				while ((in_array($retour_analyse=$this->analyserLigne($line,$i),array(LIGNE_IMAGE_SEULEMENT, LIGNE_VIDE))) && ($i<=$rowcount)) {
158
				while ((in_array($retour_analyse=$this->analyserLigne($line,$i),array(LIGNE_IMAGE_SEULEMENT, LIGNE_VIDE))) && ($i<=$rowcount)) {
159
					if  ($retour_analyse==LIGNE_IMAGE_SEULEMENT) {
159
					if  ($retour_analyse==LIGNE_IMAGE_SEULEMENT) {
160
						$this->traiterLigneComplement($line,$i,$pairs['utilisateur'],$id_obs); // images supplementaires
160
						$this->traiterLigneComplement($line,$i,$pairs['utilisateur'],$id_obs); // images supplementaires
161
					}
161
					}
162
					else {
162
					else {
163
						// print "vide";
163
						// print "vide";
164
					}
164
					}
165
					$i++;
165
					$i++;
166
				}	
166
				}	
167
			}
167
			}
168
		}
168
		}
169
		$message = '';
169
		$message = '';
170
		
170
		
171
		if($this->cpt_images_liees > 0) {
171
		if($this->cpt_images_liees > 0) {
172
			$message = $this->cpt_images_liees.' images liees pour ';
172
			$message = $this->cpt_images_liees.' images liees pour ';
173
		}
173
		}
174
		
174
		
175
		$message .= $cpt_obs;
175
		$message .= $cpt_obs;
176
		print $message;
176
		print $message;
177
	}
177
	}
178
 
178
 
179
	function analyserLigne($line,$i) {
179
	function analyserLigne($line,$i) {
180
		
180
		
181
		$ligne_vide=true;
181
		$ligne_vide=true;
182
		$ligne_image_seulement=true;
182
		$ligne_image_seulement=true;
183
		$ligne_normale=true;
183
		$ligne_normale=true;
184
		
184
		
185
		$ligne_identique_sauf_image = true;
185
		$ligne_identique_sauf_image = true;
186
		
186
		
187
		foreach ($this->format_observation as $colonne) {
187
		foreach ($this->format_observation as $colonne) {
188
			
188
			
189
			if($i < 1) {
189
			if($i < 1) {
190
				$ligne_identique_sauf_image = false;
190
				$ligne_identique_sauf_image = false;
191
			} else {
191
			} else {
192
				
192
				
193
				if($colonne!= IMAGE && isset($line[$colonne]) && isset($line[$colonne][$i - 1]) && isset($line[$colonne][$i]) 
193
				if($colonne!= IMAGE && isset($line[$colonne]) && isset($line[$colonne][$i - 1]) && isset($line[$colonne][$i]) 
194
					&& $line[$colonne][$i - 1] != $line[$colonne][$i] && $line[$colonne][$i] != '') {
194
					&& $line[$colonne][$i - 1] != $line[$colonne][$i] && $line[$colonne][$i] != '') {
195
					$ligne_identique_sauf_image = false;
195
					$ligne_identique_sauf_image = false;
196
				}
196
				}
197
			} 
197
			} 
198
			
198
			
199
			if (isset ($line[$colonne][$i]) && $line[$colonne][$i]!='') {
199
			if (isset ($line[$colonne][$i]) && $line[$colonne][$i]!='') {
200
				if ($colonne!=IMAGE) {
200
				if ($colonne!=IMAGE) {
201
					$ligne_image_seulement=false;
201
					$ligne_image_seulement=false;
202
					$ligne_vide=false;
202
					$ligne_vide=false;
203
				}		
203
				}		
204
				$ligne_vide=false;
204
				$ligne_vide=false;
205
			}		
205
			}		
206
		}
206
		}
207
		
207
		
208
		if ($ligne_vide) {
208
		if ($ligne_vide) {
209
			return LIGNE_VIDE;
209
			return LIGNE_VIDE;
210
		}
210
		}
211
		else {
211
		else {
212
			if ($ligne_image_seulement || $ligne_identique_sauf_image) {
212
			if ($ligne_image_seulement || $ligne_identique_sauf_image) {
213
				return LIGNE_IMAGE_SEULEMENT;
213
				return LIGNE_IMAGE_SEULEMENT;
214
			}
214
			}
215
			else {
215
			else {
216
				return LIGNE_NORMALE;
216
				return LIGNE_NORMALE;
217
			}
217
			}
218
		}
218
		}
219
	}
219
	}
220
 
220
 
221
	function traiterLigne($line,$i,$utilisateur) { 
221
	function traiterLigne($line,$i,$utilisateur) { 
222
		// Controle donnee et insertion
222
		// Controle donnee et insertion
223
		$info_image=array();
223
		$info_image=array();
224
		$info_transmettre = "0";
224
		$info_transmettre = "0";
225
		$info_espece = array('en_id_nom' => '',
225
		$info_espece = array('en_id_nom' => '',
226
			'nom_sel' => '',
226
			'nom_sel' => '',
227
			'nom_sel_nn' => '',
227
			'nom_sel_nn' => '',
228
			'nom_ret' => '',
228
			'nom_ret' => '',
229
			'nom_ret_nn' => '',
229
			'nom_ret_nn' => '',
230
			'nt' => '',
230
			'nt' => '',
231
			'famille' => ''
231
			'famille' => ''
232
		);
232
		);
233
		$info_commune = array('nom' => '', 'code' => '');
233
		$info_commune = array('nom' => '', 'code' => '');
234
		
234
		
235
		foreach ($this->format_observation as $colonne) {
235
		foreach ($this->format_observation as $colonne) {
236
			if (isset ($line[$colonne][$i]) && $line[$colonne][$i]!='') {
236
			if (isset ($line[$colonne][$i]) && $line[$colonne][$i]!='') {
237
				switch ($colonne) {  // On ne garde que les colonnes que l'on souhaite traiter
237
				switch ($colonne) {  // On ne garde que les colonnes que l'on souhaite traiter
238
					case COMMUNE:
238
					case COMMUNE:
239
						$info_commune = $this->traiterCommune($line[COMMUNE][$i]);
239
						$info_commune = $this->traiterCommune($line[COMMUNE][$i]);
240
						break;
240
						break;
241
					case LIEUDIT:
241
					case LIEUDIT:
242
						$info_lieudit = $this->traiterLieudit($line[LIEUDIT][$i]);
242
						$info_lieudit = $this->traiterLieudit($line[LIEUDIT][$i]);
243
						break;
243
						break;
244
					case STATION:
244
					case STATION:
245
						$info_station = $this->traiterStation($line[STATION][$i]);
245
						$info_station = $this->traiterStation($line[STATION][$i]);
246
						break;
246
						break;
247
					case MILIEU:
247
					case MILIEU:
248
						$info_milieu = $this->traiterMilieu($line[MILIEU][$i]);
248
						$info_milieu = $this->traiterMilieu($line[MILIEU][$i]);
249
						break;
249
						break;
250
	                case DEPARTEMENT:
250
	                case DEPARTEMENT:
251
	                	$dpt = $this->traiterDepartement($line[DEPARTEMENT][$i]);
251
	                	$dpt = $this->traiterDepartement($line[DEPARTEMENT][$i]);
252
	                	if(is_numeric($dpt) && strlen($dpt == 5) && $info_commune['code'] == 'NULL') {          		
252
	                	if(is_numeric($dpt) && strlen($dpt == 5) && $info_commune['code'] == 'NULL') {          		
253
	                		$info_commune['code'] = $dpt;
253
	                		$info_commune['code'] = $dpt;
254
	                	}
254
	                	}
255
						break;
255
						break;
256
					case LATITUDE:
256
					case LATITUDE:
257
						$info_latitude = $this->traiterLatitude($line[LATITUDE][$i]);
257
						$info_latitude = $this->traiterLatitude($line[LATITUDE][$i]);
258
						break;
258
						break;
259
					case LONGITUDE:
259
					case LONGITUDE:
260
						$info_longitude = $this->traiterLongitude($line[LONGITUDE][$i]);
260
						$info_longitude = $this->traiterLongitude($line[LONGITUDE][$i]);
261
						break;
261
						break;
262
					case NOTES:
262
					case NOTES:
263
						$info_notes = $this->traiterNotes($line[NOTES][$i]);
263
						$info_notes = $this->traiterNotes($line[NOTES][$i]);
264
						break;
264
						break;
265
					case DATEOBS:
265
					case DATEOBS:
266
						$info_dateobs = $this->traiterDateObs($line[DATEOBS][$i]);
266
						$info_dateobs = $this->traiterDateObs($line[DATEOBS][$i]);
267
						break;
267
						break;
268
					case TRANSMETTRE:
268
					case TRANSMETTRE:
269
						$info_transmettre = $this->traiterTransmettre($line[TRANSMETTRE][$i]);
269
						$info_transmettre = $this->traiterTransmettre($line[TRANSMETTRE][$i]);
270
					break;
270
					break;
271
					case ESPECE:
271
					case ESPECE:
272
						$chercheur_infos_taxon = new RechercheInfosTaxon($this->config);
272
						$chercheur_infos_taxon = new RechercheInfosTaxon($this->config);
273
						$resultat_recherche_espece = $chercheur_infos_taxon->rechercherInfosSurTexteCodeOuNumTax($line[ESPECE][$i]);
273
						$resultat_recherche_espece = $chercheur_infos_taxon->rechercherInfosSurTexteCodeOuNumTax($line[ESPECE][$i]);
274
	                    if (isset($resultat_recherche_espece['en_id_nom']) && $resultat_recherche_espece['en_id_nom']!='') {
274
	                    if (isset($resultat_recherche_espece['en_id_nom']) && $resultat_recherche_espece['en_id_nom']!='') {
275
	                    	$info_espece['nom_sel'] = $resultat_recherche_espece['nom_sel'];
275
	                    	$info_espece['nom_sel'] = $resultat_recherche_espece['nom_sel'];
276
	                    	$info_espece['nom_sel_nn'] = $resultat_recherche_espece['en_id_nom'];
276
	                    	$info_espece['nom_sel_nn'] = $resultat_recherche_espece['en_id_nom'];
277
	                        $complement = $chercheur_infos_taxon->rechercherInformationsComplementairesSurNumNom($resultat_recherche_espece['en_id_nom']);
277
	                        $complement = $chercheur_infos_taxon->rechercherInformationsComplementairesSurNumNom($resultat_recherche_espece['en_id_nom']);
278
	                        $info_espece['nom_ret'] = $complement['Nom_Retenu'];
278
	                        $info_espece['nom_ret'] = $complement['Nom_Retenu'];
279
	                        $info_espece['nom_ret_nn'] = $complement['Num_Nom_Retenu'];
279
	                        $info_espece['nom_ret_nn'] = $complement['Num_Nom_Retenu'];
280
	                        $info_espece['nt'] = $complement['Num_Taxon'];
280
	                        $info_espece['nt'] = $complement['Num_Taxon'];
281
	                        $info_espece['famille'] = $complement['Famille'];
281
	                        $info_espece['famille'] = $complement['Famille'];
282
	                    } else {
282
	                    } else {
283
	                    	$info_espece['nom_sel'] = $line[ESPECE][$i];
283
	                    	$info_espece['nom_sel'] = $line[ESPECE][$i];
284
	                    }
284
	                    }
285
	                    break;
285
	                    break;
286
					case IMAGE:
286
					case IMAGE:
287
						$info_image=$this->traiterImage($line[IMAGE][$i],$utilisateur); // Image separee par des / +  utilisateur
287
						$info_image=$this->traiterImage($line[IMAGE][$i],$utilisateur); // Image separee par des / +  utilisateur
288
						break;
288
						break;
289
				}
289
				}
290
			}
290
			}
291
			else {	
291
			else {	
292
			 	switch($colonne) {
292
			 	switch($colonne) {
293
					case COMMUNE:
293
					case COMMUNE:
294
						$info_commune['nom']="";
294
						$info_commune['nom']="";
295
						break;
295
						break;
296
					case LIEUDIT:
296
					case LIEUDIT:
297
						$info_lieudit="";
297
						$info_lieudit="";
298
						break;
298
						break;
299
					case STATION:
299
					case STATION:
300
						$info_station="";
300
						$info_station="";
301
						break;
301
						break;
302
					case MILIEU:
302
					case MILIEU:
303
						$info_milieu="";
303
						$info_milieu="";
304
						break;
304
						break;
305
					case DEPARTEMENT:
305
					case DEPARTEMENT:
306
			            if (!isset ($info_commune['code']) || $info_commune['code']=='') {
306
			            if (!isset ($info_commune['code']) || $info_commune['code']=='') {
307
						    $info_commune['code']="";
307
						    $info_commune['code']="";
308
	                    }
308
	                    }
309
						break;
309
						break;
310
					case LATITUDE:
310
					case LATITUDE:
311
						$info_latitude = "";
311
						$info_latitude = "";
312
						break;
312
						break;
313
					case LONGITUDE:
313
					case LONGITUDE:
314
						$info_longitude = "";
314
						$info_longitude = "";
315
						break;
315
						break;
316
					case NOTES:
316
					case NOTES:
317
						$info_notes='';
317
						$info_notes='';
318
						break;
318
						break;
319
					case TRANSMETTRE:
319
					case TRANSMETTRE:
320
						$info_transmettre = "0";
320
						$info_transmettre = "0";
321
					break;
321
					break;
322
				}
322
				}
323
			}
323
			}
324
		}
324
		}
325
	
325
	
326
        $this->dernier_ordre++;
326
        $this->dernier_ordre++;
327
        list($jour,$mois,$annee) = isset($info_dateobs) ? explode("/",$info_dateobs) : array(null,null,null);
327
        list($jour,$mois,$annee) = isset($info_dateobs) ? explode("/",$info_dateobs) : array(null,null,null);
328
        $info_dateobs=$annee."-".$mois."-".$jour." 0:0:0";
328
        $info_dateobs=$annee."-".$mois."-".$jour." 0:0:0";
329
        $requete  = "INSERT INTO cel_obs (".
329
        $requete  = "INSERT INTO cel_obs (".
330
	        "ce_utilisateur,ordre,".
330
	        "ce_utilisateur,ordre,".
331
	        "nom_sel,nom_sel_nn,nom_ret,nom_ret_nn,nt,famille,".
331
	        "nom_sel,nom_sel_nn,nom_ret,nom_ret_nn,nt,famille,".
332
	        "zone_geo,ce_zone_geo,".
332
	        "zone_geo,ce_zone_geo,".
333
	        "date_observation,".
333
	        "date_observation,".
334
	        "lieudit,station, milieu, commentaire, transmission, ".
334
	        "lieudit,station, milieu, commentaire, transmission, ".
335
	        "date_creation,date_modification,latitude,longitude) ".
335
	        "date_creation,date_modification,latitude,longitude) ".
336
	        " VALUES(".$this->proteger($utilisateur).",".
336
	        " VALUES(".$this->proteger($utilisateur).",".
337
	        $this->proteger($this->dernier_ordre).",".
337
	        $this->proteger($this->dernier_ordre).",".
338
	        $this->proteger($info_espece['nom_sel']).",".
338
	        $this->proteger($info_espece['nom_sel']).",".
339
	        $this->proteger($info_espece['nom_sel_nn']).",".
339
	        $this->proteger($info_espece['nom_sel_nn']).",".
340
	        $this->proteger($info_espece['nom_ret']).",".
340
	        $this->proteger($info_espece['nom_ret']).",".
341
	        $this->proteger($info_espece['nom_ret_nn']).",".
341
	        $this->proteger($info_espece['nom_ret_nn']).",".
342
	        $this->proteger($info_espece['nt']).",".
342
	        $this->proteger($info_espece['nt']).",".
343
	        $this->proteger($info_espece['famille']).",".
343
	        $this->proteger($info_espece['famille']).",".
344
	        $this->proteger($info_commune['nom']).",".
344
	        $this->proteger($info_commune['nom']).",".
345
	        $this->proteger('INSEE-C:'.$info_commune['code']).",".
345
	        $this->proteger('INSEE-C:'.$info_commune['code']).",".
346
	        $this->proteger($info_dateobs).",".
346
	        $this->proteger($info_dateobs).",".
347
	        $this->proteger($info_lieudit).",".
347
	        $this->proteger($info_lieudit).",".
348
	        $this->proteger($info_station).",".
348
	        $this->proteger($info_station).",".
349
	        $this->proteger($info_milieu).",".
349
	        $this->proteger($info_milieu).",".
350
	        $this->proteger($info_notes).",".
350
	        $this->proteger($info_notes).",".
351
	        $this->proteger($info_transmettre).",".
351
	        $this->proteger($info_transmettre).",".
352
	        "now() , now(),".
352
	        "now() , now(),".
353
	        $this->proteger($info_latitude).",".
353
	        $this->proteger($info_latitude).",".
354
	        $this->proteger($info_longitude).")";
354
	        $this->proteger($info_longitude).")";
355
	
355
	
356
		$insertion = $this->executer($requete);
356
		$insertion = $this->executer($requete);
357
		
357
		
358
		$requete_id_obs = 'SELECT id_observation FROM cel_obs WHERE ordre = '.$this->proteger($this->dernier_ordre).' AND ce_utilisateur = '.$this->proteger($utilisateur);
358
		$requete_id_obs = 'SELECT id_observation FROM cel_obs WHERE ordre = '.$this->proteger($this->dernier_ordre).' AND ce_utilisateur = '.$this->proteger($utilisateur);
359
		$resultat_id_obs = $this->requeter($requete_id_obs);
359
		$resultat_id_obs = $this->requeter($requete_id_obs);
360
			
360
			
361
		$id_obs = $resultat_id_obs[0]['id_observation'];
361
		$id_obs = $resultat_id_obs[0]['id_observation'];
362
		
362
		
363
		// creation lien image
363
		// creation lien image
364
		foreach ($info_image as $pic) {
364
		foreach ($info_image as $pic) {
365
				
365
				
366
			$requete_liaison = 'INSERT INTO cel_obs_images (id_image, id_utilisateur, id_observation ) VALUES ('.$this->proteger($pic['id_image']).','.$this->proteger($utilisateur).', '.$id_obs.') ON DUPLICATE KEY UPDATE id_image = id_image ';	
366
			$requete_liaison = 'INSERT INTO cel_obs_images (id_image, id_observation ) VALUES ('.$this->proteger($pic['id_image']).', '.$id_obs.') ON DUPLICATE KEY UPDATE id_image = id_image ';	
367
			$liaison = $this->executer($requete_liaison);
367
			$liaison = $this->executer($requete_liaison);
368
            if ($liaison !== false) {
368
            if ($liaison !== false) {
369
            	$this->cpt_images_liees++;
369
            	$this->cpt_images_liees++;
370
            } else {
370
            } else {
371
            	return false;    	
371
            	return false;    	
372
            }
372
            }
373
		}
373
		}
374
	
374
	
375
		return $id_obs;
375
		return $id_obs;
376
	}
376
	}
377
 
377
 
378
	function traiterLigneComplement($line,$i,$utilisateur, $id_obs = null) {
378
	function traiterLigneComplement($line,$i,$utilisateur, $id_obs = null) {
379
	
379
	
380
		$info_image=$this->traiterImage($line[IMAGE][$i],$utilisateur); // Image separee par des / +  utilisateur	
380
		$info_image=$this->traiterImage($line[IMAGE][$i],$utilisateur); // Image separee par des / +  utilisateur	
381
		// creation lien image
381
		// creation lien image
382
		foreach ($info_image as $pic) {	
382
		foreach ($info_image as $pic) {	
383
			$requete = 'INSERT INTO cel_obs_images (id_image, id_utilisateur, id_observation) VALUES ('.$this->proteger($pic['id_image']).','.$this->proteger($utilisateur).', '.$this->proteger($id_obs).') ON DUPLICATE KEY UPDATE id_image = id_image' ;	
383
			$requete = 'INSERT INTO cel_obs_images (id_image, id_observation) VALUES ('.$this->proteger($pic['id_image']).', '.$this->proteger($id_obs).') ON DUPLICATE KEY UPDATE id_image = id_image' ;	
384
			$resultat_liaison = $this->executer($requete);
384
			$resultat_liaison = $this->executer($requete);
385
	    	if ($resultat_liaison !== false) {
385
	    	if ($resultat_liaison !== false) {
386
	    		$this->cpt_images_liees++;
386
	    		$this->cpt_images_liees++;
387
	    	} else {
387
	    	} else {
388
	    		return false;
388
	    		return false;
389
	    	}
389
	    	}
390
		}
390
		}
391
	}
391
	}
392
	
392
	
393
	function traiterCommune($identifiant_commune) {  
393
	function traiterCommune($identifiant_commune) {  
394
		// Recherche correspondance sur nom, si pas unique, correspondance dep. sinon code insee
394
		// Recherche correspondance sur nom, si pas unique, correspondance dep. sinon code insee
395
	    $identifiant_commune=trim($identifiant_commune);
395
	    $identifiant_commune=trim($identifiant_commune);
396
	    $identifiant_commune=utf8_encode($identifiant_commune); // FIXME : devrait deja etre en utf8 a ce niveau
396
	    $identifiant_commune=utf8_encode($identifiant_commune); // FIXME : devrait deja etre en utf8 a ce niveau
397
	
397
	
398
		preg_match('/(.*) \(([0-9][0-9]*)\)/',$identifiant_commune,$elements);
398
		preg_match('/(.*) \(([0-9][0-9]*)\)/',$identifiant_commune,$elements);
399
	
399
	
400
		if (isset($elements[1])) { // commune + departement : montpellier (34)
400
		if (isset($elements[1])) { // commune + departement : montpellier (34)
401
			$nom_commune=$elements[1];
401
			$nom_commune=$elements[1];
402
			$code_commune=$elements[2];
402
			$code_commune=$elements[2];
403
	 	    $requete="SELECT DISTINCT nom, code  FROM cel_zone_geo WHERE nom = ".$this->proteger($nom_commune)." AND code LIKE ".$this->proteger($code_commune.'%');
403
	 	    $requete="SELECT DISTINCT nom, code  FROM cel_zone_geo WHERE nom = ".$this->proteger($nom_commune)." AND code LIKE ".$this->proteger($code_commune.'%');
404
		}
404
		}
405
		else { // Code insee seul 
405
		else { // Code insee seul 
406
	        preg_match('/([0-9][0-9]*)|(2A[0-9][0-9]*)|(2B[0-9][0-9]*)/',$identifiant_commune,$elements);
406
	        preg_match('/([0-9][0-9]*)|(2A[0-9][0-9]*)|(2B[0-9][0-9]*)/',$identifiant_commune,$elements);
407
	        if (isset($elements[1])) { // code insee  commune
407
	        if (isset($elements[1])) { // code insee  commune
408
	            $code_insee_commune=$elements[1];
408
	            $code_insee_commune=$elements[1];
409
	            $requete="SELECT DISTINCT nom, code  FROM cel_zones_geo WHERE code = ".$this->proteger($code_insee_commune);
409
	            $requete="SELECT DISTINCT nom, code  FROM cel_zones_geo WHERE code = ".$this->proteger($code_insee_commune);
410
	        }	
410
	        }	
411
	        else { // Commune seule (le departement sera recupere dans la colonne departement si elle est presente, on prend le risque ici de retourner une mauvaise
411
	        else { // Commune seule (le departement sera recupere dans la colonne departement si elle est presente, on prend le risque ici de retourner une mauvaise
412
	               // Commune
412
	               // Commune
413
	            preg_match('/(.*)/',$identifiant_commune,$elements);
413
	            preg_match('/(.*)/',$identifiant_commune,$elements);
414
	            if (isset($elements[1])) { // commune 
414
	            if (isset($elements[1])) { // commune 
415
	                $nom_commune=$elements[1];
415
	                $nom_commune=$elements[1];
416
	                $nom_commune=trim($nom_commune);
416
	                $nom_commune=trim($nom_commune);
417
	                $nom_commune=utf8_decode($nom_commune);
417
	                $nom_commune=utf8_decode($nom_commune);
418
	                $nom_commune=cp1252_to_utf8($nom_commune);
418
	                $nom_commune=cp1252_to_utf8($nom_commune);
419
	                $nom_commune=remove_accent($nom_commune);
419
	                $nom_commune=remove_accent($nom_commune);
420
	                $nom_commune=preg_replace("/ /","%",$nom_commune);
420
	                $nom_commune=preg_replace("/ /","%",$nom_commune);
421
	                $requete="SELECT DISTINCT nom, code  FROM cel_zones_geo WHERE nom like ".$this->proteger($nom_commune.'%');
421
	                $requete="SELECT DISTINCT nom, code  FROM cel_zones_geo WHERE nom like ".$this->proteger($nom_commune.'%');
422
	            }
422
	            }
423
	        }
423
	        }
424
		}
424
		}
425
	
425
	
426
		$resultat_commune = $this->requeter($requete);
426
		$resultat_commune = $this->requeter($requete);
427
		
427
		
428
		// cas de la commune introuvable dans le référentiel
428
		// cas de la commune introuvable dans le référentiel
429
		if(!is_array($resultat_commune) || count($resultat_commune) == 0) {
429
		if(!is_array($resultat_commune) || count($resultat_commune) == 0) {
430
			$resultat_commune['nom'] = fix_latin($identifiant_commune);
430
			$resultat_commune['nom'] = fix_latin($identifiant_commune);
431
			$resultat_commune['code'] = 'NULL';
431
			$resultat_commune['code'] = 'NULL';
432
		} else {
432
		} else {
433
			$resultat_commune = $resultat_commune[0];
433
			$resultat_commune = $resultat_commune[0];
434
		}
434
		}
435
			
435
			
436
		return $resultat_commune;
436
		return $resultat_commune;
437
	}
437
	}
438
 
438
 
439
	function traiterLieudit($lieudit) { 
439
	function traiterLieudit($lieudit) { 
440
		// texte libre
440
		// texte libre
441
	    $lieudit=fix_latin($lieudit);
441
	    $lieudit=fix_latin($lieudit);
442
		return trim($lieudit);
442
		return trim($lieudit);
443
	}
443
	}
444
 
444
 
445
	function traiterStation($station) { 
445
	function traiterStation($station) { 
446
		// texte libre
446
		// texte libre
447
	    $station=fix_latin($station);
447
	    $station=fix_latin($station);
448
		return trim($station);
448
		return trim($station);
449
	}
449
	}
450
 
450
 
451
	function traiterMilieu($milieu) { 
451
	function traiterMilieu($milieu) { 
452
		// texte libre
452
		// texte libre
453
	    $milieu=fix_latin($milieu);
453
	    $milieu=fix_latin($milieu);
454
		return trim($milieu);
454
		return trim($milieu);
455
	}
455
	}
456
 
456
 
457
	function traiterDepartement($departement) { 
457
	function traiterDepartement($departement) { 
458
		// texte libre
458
		// texte libre
459
		if(is_numeric($departement) && strlen($departement) == 4) {
459
		if(is_numeric($departement) && strlen($departement) == 4) {
460
			$departement = "0"+$departement;
460
			$departement = "0"+$departement;
461
		}
461
		}
462
	
462
	
463
		if(is_numeric($departement) && $departement <= 9) {
463
		if(is_numeric($departement) && $departement <= 9) {
464
			$departement = "0"+$departement;
464
			$departement = "0"+$departement;
465
		}
465
		}
466
		
466
		
467
		return utf8_encode(trim($departement));
467
		return utf8_encode(trim($departement));
468
	}
468
	}
469
 
469
 
470
	function traiterLatitude($latitude) {	
470
	function traiterLatitude($latitude) {	
471
		//  verifier formal decimal + limite france ? TODO 
471
		//  verifier formal decimal + limite france ? TODO 
472
		return trim($latitude);
472
		return trim($latitude);
473
	}
473
	}
474
	
474
	
475
	function traiterLongitude($longitude) { 
475
	function traiterLongitude($longitude) { 
476
		// verifier format decimal + limite france ? TODO 
476
		// verifier format decimal + limite france ? TODO 
477
		return trim($longitude);
477
		return trim($longitude);
478
	}
478
	}
479
	
479
	
480
	function traiterNotes($notes) { 
480
	function traiterNotes($notes) { 
481
		// texte libre
481
		// texte libre
482
	    $notes=remove_accent($notes);
482
	    $notes=remove_accent($notes);
483
		return utf8_encode(trim($notes));
483
		return utf8_encode(trim($notes));
484
	}
484
	}
485
	
485
	
486
	function traiterDateObs($dateobs) { 
486
	function traiterDateObs($dateobs) { 
487
		// verifier jj/mm/aaaa sinon date vide TODO 
487
		// verifier jj/mm/aaaa sinon date vide TODO 
488
		$date = trim($dateobs);
488
		$date = trim($dateobs);
489
		if(!preg_match("#[0-9]{2}/[0-9]{2}/([0-9]{4}|[0-9]{2})#", $date)) {
489
		if(!preg_match("#[0-9]{2}/[0-9]{2}/([0-9]{4}|[0-9]{2})#", $date)) {
490
			$date = '00/00/0000';
490
			$date = '00/00/0000';
491
		}
491
		}
492
		return $date;
492
		return $date;
493
	}
493
	}
494
 
494
 
495
	function traiterTransmettre($transmettre) {		
495
	function traiterTransmettre($transmettre) {		
496
		$transmission = '0';		
496
		$transmission = '0';		
497
		if (trim($transmettre) == "1" || trim($transmettre) == "oui") {	
497
		if (trim($transmettre) == "1" || trim($transmettre) == "oui") {	
498
			$transmission = '1';
498
			$transmission = '1';
499
		}			
499
		}			
500
		return $transmission;
500
		return $transmission;
501
	}
501
	}
502
	
502
	
503
	function traiterImage($images,$utilisateur) { // recherche id image de ce nom 	
503
	function traiterImage($images,$utilisateur) { // recherche id image de ce nom 	
504
		$liste_images = explode("/",$images) ;
504
		$liste_images = explode("/",$images) ;
505
		$row =array();
505
		$row =array();
506
	   	foreach($liste_images as $image) {
506
	   	foreach($liste_images as $image) {
-
 
507
			$image = remove_accent(fix_latin($image));
507
			$requete = "SELECT * FROM cel_images WHERE ce_utilisateur = ".$this->proteger($utilisateur)." AND nom_original= ".$this->proteger($image);
508
			$requete = "SELECT * FROM cel_images WHERE ce_utilisateur = ".$this->proteger($utilisateur)." AND nom_original= ".$this->proteger($image);
508
			$ligne = $this->requeter($requete);
509
			$ligne = $this->requeter($requete);
509
		    if(is_array($ligne) && !empty($ligne)) {
510
		    if(is_array($ligne) && !empty($ligne)) {
510
		    	$row[] = $ligne[0];
511
		    	$row[] = $ligne[0];
511
		    }
512
		    }
512
		}
513
		}
513
		return $row;
514
		return $row;
514
	}
515
	}
515
}
516
}
516
 
517
 
517
function init_byte_map(){
518
function init_byte_map(){
518
    $byte_map = array();
519
    $byte_map = array();
519
    for($x=128;$x<256;++$x){
520
    for($x=128;$x<256;++$x){
520
        $byte_map[chr($x)]=utf8_encode(chr($x));
521
        $byte_map[chr($x)]=utf8_encode(chr($x));
521
    }
522
    }
522
    $cp1252_map=array(
523
    $cp1252_map=array(
523
            "\x80"=>"\xE2\x82\xAC",    // EURO SIGN
524
            "\x80"=>"\xE2\x82\xAC",    // EURO SIGN
524
            "\x82" => "\xE2\x80\x9A",  // SINGLE LOW-9 QUOTATION MARK
525
            "\x82" => "\xE2\x80\x9A",  // SINGLE LOW-9 QUOTATION MARK
525
            "\x83" => "\xC6\x92",      // LATIN SMALL LETTER F WITH HOOK
526
            "\x83" => "\xC6\x92",      // LATIN SMALL LETTER F WITH HOOK
526
            "\x84" => "\xE2\x80\x9E",  // DOUBLE LOW-9 QUOTATION MARK
527
            "\x84" => "\xE2\x80\x9E",  // DOUBLE LOW-9 QUOTATION MARK
527
            "\x85" => "\xE2\x80\xA6",  // HORIZONTAL ELLIPSIS
528
            "\x85" => "\xE2\x80\xA6",  // HORIZONTAL ELLIPSIS
528
            "\x86" => "\xE2\x80\xA0",  // DAGGER
529
            "\x86" => "\xE2\x80\xA0",  // DAGGER
529
            "\x87" => "\xE2\x80\xA1",  // DOUBLE DAGGER
530
            "\x87" => "\xE2\x80\xA1",  // DOUBLE DAGGER
530
            "\x88" => "\xCB\x86",      // MODIFIER LETTER CIRCUMFLEX ACCENT
531
            "\x88" => "\xCB\x86",      // MODIFIER LETTER CIRCUMFLEX ACCENT
531
            "\x89" => "\xE2\x80\xB0",  // PER MILLE SIGN
532
            "\x89" => "\xE2\x80\xB0",  // PER MILLE SIGN
532
            "\x8A" => "\xC5\xA0",      // LATIN CAPITAL LETTER S WITH CARON
533
            "\x8A" => "\xC5\xA0",      // LATIN CAPITAL LETTER S WITH CARON
533
            "\x8B" => "\xE2\x80\xB9",  // SINGLE LEFT-POINTING ANGLE QUOTATION MARK
534
            "\x8B" => "\xE2\x80\xB9",  // SINGLE LEFT-POINTING ANGLE QUOTATION MARK
534
            "\x8C" => "\xC5\x92",      // LATIN CAPITAL LIGATURE OE
535
            "\x8C" => "\xC5\x92",      // LATIN CAPITAL LIGATURE OE
535
            "\x8E" => "\xC5\xBD",      // LATIN CAPITAL LETTER Z WITH CARON
536
            "\x8E" => "\xC5\xBD",      // LATIN CAPITAL LETTER Z WITH CARON
536
            "\x91" => "\xE2\x80\x98",  // LEFT SINGLE QUOTATION MARK
537
            "\x91" => "\xE2\x80\x98",  // LEFT SINGLE QUOTATION MARK
537
            "\x92" => "\xE2\x80\x99",  // RIGHT SINGLE QUOTATION MARK
538
            "\x92" => "\xE2\x80\x99",  // RIGHT SINGLE QUOTATION MARK
538
            "\x93" => "\xE2\x80\x9C",  // LEFT DOUBLE QUOTATION MARK
539
            "\x93" => "\xE2\x80\x9C",  // LEFT DOUBLE QUOTATION MARK
539
            "\x94" => "\xE2\x80\x9D",  // RIGHT DOUBLE QUOTATION MARK
540
            "\x94" => "\xE2\x80\x9D",  // RIGHT DOUBLE QUOTATION MARK
540
            "\x95" => "\xE2\x80\xA2",  // BULLET
541
            "\x95" => "\xE2\x80\xA2",  // BULLET
541
            "\x96" => "\xE2\x80\x93",  // EN DASH
542
            "\x96" => "\xE2\x80\x93",  // EN DASH
542
            "\x97" => "\xE2\x80\x94",  // EM DASH
543
            "\x97" => "\xE2\x80\x94",  // EM DASH
543
            "\x98" => "\xCB\x9C",      // SMALL TILDE
544
            "\x98" => "\xCB\x9C",      // SMALL TILDE
544
            "\x99" => "\xE2\x84\xA2",  // TRADE MARK SIGN
545
            "\x99" => "\xE2\x84\xA2",  // TRADE MARK SIGN
545
            "\x9A" => "\xC5\xA1",      // LATIN SMALL LETTER S WITH CARON
546
            "\x9A" => "\xC5\xA1",      // LATIN SMALL LETTER S WITH CARON
546
            "\x9B" => "\xE2\x80\xBA",  // SINGLE RIGHT-POINTING ANGLE QUOTATION MARK
547
            "\x9B" => "\xE2\x80\xBA",  // SINGLE RIGHT-POINTING ANGLE QUOTATION MARK
547
            "\x9C" => "\xC5\x93",      // LATIN SMALL LIGATURE OE
548
            "\x9C" => "\xC5\x93",      // LATIN SMALL LIGATURE OE
548
            "\x9E" => "\xC5\xBE",      // LATIN SMALL LETTER Z WITH CARON
549
            "\x9E" => "\xC5\xBE",      // LATIN SMALL LETTER Z WITH CARON
549
            "\x9F" => "\xC5\xB8"       // LATIN CAPITAL LETTER Y WITH DIAERESIS
550
            "\x9F" => "\xC5\xB8"       // LATIN CAPITAL LETTER Y WITH DIAERESIS
550
                );
551
                );
551
    foreach($cp1252_map as $k=>$v){
552
    foreach($cp1252_map as $k=>$v){
552
        $byte_map[$k]=$v;
553
        $byte_map[$k]=$v;
553
    }
554
    }
554
    
555
    
555
    return $byte_map;
556
    return $byte_map;
556
}
557
}
557
 
558
 
558
function fix_latin($instr){
559
function fix_latin($instr){
559
    
560
    
560
    $byte_map = init_byte_map();
561
    $byte_map = init_byte_map();
561
    
562
    
562
    $ascii_char='[\x00-\x7F]';
563
    $ascii_char='[\x00-\x7F]';
563
    $cont_byte='[\x80-\xBF]';
564
    $cont_byte='[\x80-\xBF]';
564
    $utf8_2='[\xC0-\xDF]'.$cont_byte;
565
    $utf8_2='[\xC0-\xDF]'.$cont_byte;
565
    $utf8_3='[\xE0-\xEF]'.$cont_byte.'{2}';
566
    $utf8_3='[\xE0-\xEF]'.$cont_byte.'{2}';
566
    $utf8_4='[\xF0-\xF7]'.$cont_byte.'{3}';
567
    $utf8_4='[\xF0-\xF7]'.$cont_byte.'{3}';
567
    $utf8_5='[\xF8-\xFB]'.$cont_byte.'{4}';
568
    $utf8_5='[\xF8-\xFB]'.$cont_byte.'{4}';
568
    
569
    
569
    $nibble_good_chars = "@^($ascii_char+|$utf8_2|$utf8_3|$utf8_4|$utf8_5)(.*)$@s";
570
    $nibble_good_chars = "@^($ascii_char+|$utf8_2|$utf8_3|$utf8_4|$utf8_5)(.*)$@s";
570
 
571
 
571
    if(mb_check_encoding($instr,'UTF-8'))return $instr; // no need for the rest if it's all valid UTF-8 already
572
    if(mb_check_encoding($instr,'UTF-8'))return $instr; // no need for the rest if it's all valid UTF-8 already
572
    $outstr='';
573
    $outstr='';
573
    $char='';
574
    $char='';
574
    $rest='';
575
    $rest='';
575
    while((strlen($instr))>0){
576
    while((strlen($instr))>0){
576
        if(1==@preg_match($nibble_good_chars,$instr,$match)){
577
        if(1==@preg_match($nibble_good_chars,$instr,$match)){
577
            $char=$match[1];
578
            $char=$match[1];
578
            $rest=$match[2];
579
            $rest=$match[2];
579
            $outstr.=$char;
580
            $outstr.=$char;
580
        }elseif(1==@preg_match('@^(.)(.*)$@s',$instr,$match)){
581
        }elseif(1==@preg_match('@^(.)(.*)$@s',$instr,$match)){
581
            $char=$match[1];
582
            $char=$match[1];
582
            $rest=$match[2];
583
            $rest=$match[2];
583
            $outstr.=$byte_map[$char];
584
            $outstr.=$byte_map[$char];
584
        }
585
        }
585
        $instr=$rest;
586
        $instr=$rest;
586
    }
587
    }
587
    return $outstr;
588
    return $outstr;
588
}
589
}
589
 
590
 
590
function remove_accent($str) {
591
function remove_accent($str) {
591
  $a = array('À', 'Á', 'Â', 'Ã', 'Ä', 'Å', 'Æ', 'Ç', 'È', 'É', 'Ê', 'Ë', 'Ì', 'Í', 'Î',
592
  $a = array('À', 'Á', 'Â', 'Ã', 'Ä', 'Å', 'Æ', 'Ç', 'È', 'É', 'Ê', 'Ë', 'Ì', 'Í', 'Î',
592
             'Ï', 'Ð', 'Ñ', 'Ò', 'Ó', 'Ô', 'Õ', 'Ö', 'Ø', 'Ù', 'Ú', 'Û', 'Ü', 'Ý', 'ß',
593
             'Ï', 'Ð', 'Ñ', 'Ò', 'Ó', 'Ô', 'Õ', 'Ö', 'Ø', 'Ù', 'Ú', 'Û', 'Ü', 'Ý', 'ß',
593
             'à', 'á', 'â', 'ã', 'ä', 'å', 'æ', 'ç', 'è', 'é', 'ê', 'ë', 'ì', 'í', 'î',
594
             'à', 'á', 'â', 'ã', 'ä', 'å', 'æ', 'ç', 'è', 'é', 'ê', 'ë', 'ì', 'í', 'î',
594
             'ï', 'ñ', 'ò', 'ó', 'ô', 'õ', 'ö', 'ø', 'ù', 'ú', 'û', 'ü', 'ý', 'ÿ', 'Ā',
595
             'ï', 'ñ', 'ò', 'ó', 'ô', 'õ', 'ö', 'ø', 'ù', 'ú', 'û', 'ü', 'ý', 'ÿ', 'Ā',
595
             'ā', 'Ă', 'ă', 'Ą', 'ą', 'Ć', 'ć', 'Ĉ', 'ĉ', 'Ċ', 'ċ', 'Č', 'č', 'Ď', 'ď',
596
             'ā', 'Ă', 'ă', 'Ą', 'ą', 'Ć', 'ć', 'Ĉ', 'ĉ', 'Ċ', 'ċ', 'Č', 'č', 'Ď', 'ď',
596
             'Đ', 'đ', 'Ē', 'ē', 'Ĕ', 'ĕ', 'Ė', 'ė', 'Ę', 'ę', 'Ě', 'ě', 'Ĝ', 'ĝ', 'Ğ',
597
             'Đ', 'đ', 'Ē', 'ē', 'Ĕ', 'ĕ', 'Ė', 'ė', 'Ę', 'ę', 'Ě', 'ě', 'Ĝ', 'ĝ', 'Ğ',
597
             'ğ', 'Ġ', 'ġ', 'Ģ', 'ģ', 'Ĥ', 'ĥ', 'Ħ', 'ħ', 'Ĩ', 'ĩ', 'Ī', 'ī', 'Ĭ', 'ĭ',
598
             'ğ', 'Ġ', 'ġ', 'Ģ', 'ģ', 'Ĥ', 'ĥ', 'Ħ', 'ħ', 'Ĩ', 'ĩ', 'Ī', 'ī', 'Ĭ', 'ĭ',
598
             'Į', 'į', 'İ', 'ı', 'IJ', 'ij', 'Ĵ', 'ĵ', 'Ķ', 'ķ', 'Ĺ', 'ĺ', 'Ļ', 'ļ', 'Ľ',
599
             'Į', 'į', 'İ', 'ı', 'IJ', 'ij', 'Ĵ', 'ĵ', 'Ķ', 'ķ', 'Ĺ', 'ĺ', 'Ļ', 'ļ', 'Ľ',
599
             'ľ', 'Ŀ', 'ŀ', 'Ł', 'ł', 'Ń', 'ń', 'Ņ', 'ņ', 'Ň', 'ň', 'ʼn', 'Ō', 'ō', 'Ŏ',
600
             'ľ', 'Ŀ', 'ŀ', 'Ł', 'ł', 'Ń', 'ń', 'Ņ', 'ņ', 'Ň', 'ň', 'ʼn', 'Ō', 'ō', 'Ŏ',
600
             'ŏ', 'Ő', 'ő', 'Œ', 'œ', 'Ŕ', 'ŕ', 'Ŗ', 'ŗ', 'Ř', 'ř', 'Ś', 'ś', 'Ŝ', 'ŝ',
601
             'ŏ', 'Ő', 'ő', 'Œ', 'œ', 'Ŕ', 'ŕ', 'Ŗ', 'ŗ', 'Ř', 'ř', 'Ś', 'ś', 'Ŝ', 'ŝ',
601
             'Ş', 'ş', 'Š', 'š', 'Ţ', 'ţ', 'Ť', 'ť', 'Ŧ', 'ŧ', 'Ũ', 'ũ', 'Ū', 'ū', 'Ŭ',
602
             'Ş', 'ş', 'Š', 'š', 'Ţ', 'ţ', 'Ť', 'ť', 'Ŧ', 'ŧ', 'Ũ', 'ũ', 'Ū', 'ū', 'Ŭ',
602
             'ŭ', 'Ů', 'ů', 'Ű', 'ű', 'Ų', 'ų', 'Ŵ', 'ŵ', 'Ŷ', 'ŷ', 'Ÿ', 'Ź', 'ź', 'Ż',
603
             'ŭ', 'Ů', 'ů', 'Ű', 'ű', 'Ų', 'ų', 'Ŵ', 'ŵ', 'Ŷ', 'ŷ', 'Ÿ', 'Ź', 'ź', 'Ż',
603
             'ż', 'Ž', 'ž', 'ſ', 'ƒ', 'Ơ', 'ơ', 'Ư', 'ư', 'Ǎ', 'ǎ', 'Ǐ', 'ǐ', 'Ǒ', 'ǒ',
604
             'ż', 'Ž', 'ž', 'ſ', 'ƒ', 'Ơ', 'ơ', 'Ư', 'ư', 'Ǎ', 'ǎ', 'Ǐ', 'ǐ', 'Ǒ', 'ǒ',
604
             'Ǔ', 'ǔ', 'Ǖ', 'ǖ', 'Ǘ', 'ǘ', 'Ǚ', 'ǚ', 'Ǜ', 'ǜ', 'Ǻ', 'ǻ', 'Ǽ', 'ǽ', 'Ǿ', 'ǿ');
605
             'Ǔ', 'ǔ', 'Ǖ', 'ǖ', 'Ǘ', 'ǘ', 'Ǚ', 'ǚ', 'Ǜ', 'ǜ', 'Ǻ', 'ǻ', 'Ǽ', 'ǽ', 'Ǿ', 'ǿ');
605
             
606
             
606
  $b = array('A', 'A', 'A', 'A', 'A', 'A', 'AE', 'C', 'E', 'E', 'E', 'E', 'I', 'I', 'I',
607
  $b = array('A', 'A', 'A', 'A', 'A', 'A', 'AE', 'C', 'E', 'E', 'E', 'E', 'I', 'I', 'I',
607
             'I', 'D', 'N', 'O', 'O', 'O', 'O', 'O', 'O', 'U', 'U', 'U', 'U', 'Y', 's',
608
             'I', 'D', 'N', 'O', 'O', 'O', 'O', 'O', 'O', 'U', 'U', 'U', 'U', 'Y', 's',
608
             'a', 'a', 'a', 'a', 'a', 'a', 'ae', 'c', 'e', 'e', 'e', 'e', 'i', 'i', 'i',
609
             'a', 'a', 'a', 'a', 'a', 'a', 'ae', 'c', 'e', 'e', 'e', 'e', 'i', 'i', 'i',
609
             'i', 'n', 'o', 'o', 'o', 'o', 'o', 'o', 'u', 'u', 'u', 'u', 'y', 'y', 'A', 'a',
610
             'i', 'n', 'o', 'o', 'o', 'o', 'o', 'o', 'u', 'u', 'u', 'u', 'y', 'y', 'A', 'a',
610
             'A', 'a', 'A', 'a', 'C', 'c', 'C', 'c', 'C', 'c', 'C', 'c', 'D', 'd', 'D', 'd',
611
             'A', 'a', 'A', 'a', 'C', 'c', 'C', 'c', 'C', 'c', 'C', 'c', 'D', 'd', 'D', 'd',
611
             'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'G', 'g', 'G', 'g', 'G', 'g',
612
             'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'G', 'g', 'G', 'g', 'G', 'g',
612
             'G', 'g', 'H', 'h', 'H', 'h', 'I', 'i', 'I', 'i', 'I', 'i', 'I', 'i', 'I', 'i',
613
             'G', 'g', 'H', 'h', 'H', 'h', 'I', 'i', 'I', 'i', 'I', 'i', 'I', 'i', 'I', 'i',
613
             'IJ', 'ij', 'J', 'j', 'K', 'k', 'L', 'l', 'L', 'l', 'L', 'l', 'L', 'l', 'l', 'l',
614
             'IJ', 'ij', 'J', 'j', 'K', 'k', 'L', 'l', 'L', 'l', 'L', 'l', 'L', 'l', 'l', 'l',
614
             'N', 'n', 'N', 'n', 'N', 'n', 'n', 'O', 'o', 'O', 'o', 'O', 'o', 'OE', 'oe', 'R',
615
             'N', 'n', 'N', 'n', 'N', 'n', 'n', 'O', 'o', 'O', 'o', 'O', 'o', 'OE', 'oe', 'R',
615
             'r', 'R', 'r', 'R', 'r', 'S', 's', 'S', 's', 'S', 's', 'S', 's', 'T', 't', 'T', 't',
616
             'r', 'R', 'r', 'R', 'r', 'S', 's', 'S', 's', 'S', 's', 'S', 's', 'T', 't', 'T', 't',
616
             'T', 't', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'W', 'w', 'Y',
617
             'T', 't', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'W', 'w', 'Y',
617
             'y', 'Y', 'Z', 'z', 'Z', 'z', 'Z', 'z', 's', 'f', 'O', 'o', 'U', 'u', 'A', 'a', 'I',
618
             'y', 'Y', 'Z', 'z', 'Z', 'z', 'Z', 'z', 's', 'f', 'O', 'o', 'U', 'u', 'A', 'a', 'I',
618
             'i', 'O', 'o', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'A', 'a', 'AE', 'ae', 'O', 'o');
619
             'i', 'O', 'o', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'A', 'a', 'AE', 'ae', 'O', 'o');
619
  return str_replace($a, $b, $str);
620
  return str_replace($a, $b, $str);
620
}
621
}
621
 
622
 
622
function cp1252_to_utf8($str) {
623
function cp1252_to_utf8($str) {
623
	$cp1252_map = array ("\xc2\x80" => "\xe2\x82\xac",
624
	$cp1252_map = array ("\xc2\x80" => "\xe2\x82\xac",
624
		"\xc2\x82" => "\xe2\x80\x9a",
625
		"\xc2\x82" => "\xe2\x80\x9a",
625
		"\xc2\x83" => "\xc6\x92",    
626
		"\xc2\x83" => "\xc6\x92",    
626
		"\xc2\x84" => "\xe2\x80\x9e",
627
		"\xc2\x84" => "\xe2\x80\x9e",
627
		"\xc2\x85" => "\xe2\x80\xa6",
628
		"\xc2\x85" => "\xe2\x80\xa6",
628
		"\xc2\x86" => "\xe2\x80\xa0",
629
		"\xc2\x86" => "\xe2\x80\xa0",
629
		"\xc2\x87" => "\xe2\x80\xa1",
630
		"\xc2\x87" => "\xe2\x80\xa1",
630
		"\xc2\x88" => "\xcb\x86",
631
		"\xc2\x88" => "\xcb\x86",
631
		"\xc2\x89" => "\xe2\x80\xb0",
632
		"\xc2\x89" => "\xe2\x80\xb0",
632
		"\xc2\x8a" => "\xc5\xa0",
633
		"\xc2\x8a" => "\xc5\xa0",
633
		"\xc2\x8b" => "\xe2\x80\xb9",
634
		"\xc2\x8b" => "\xe2\x80\xb9",
634
		"\xc2\x8c" => "\xc5\x92",
635
		"\xc2\x8c" => "\xc5\x92",
635
		"\xc2\x8e" => "\xc5\xbd",
636
		"\xc2\x8e" => "\xc5\xbd",
636
		"\xc2\x91" => "\xe2\x80\x98",
637
		"\xc2\x91" => "\xe2\x80\x98",
637
		"\xc2\x92" => "\xe2\x80\x99",
638
		"\xc2\x92" => "\xe2\x80\x99",
638
		"\xc2\x93" => "\xe2\x80\x9c",
639
		"\xc2\x93" => "\xe2\x80\x9c",
639
		"\xc2\x94" => "\xe2\x80\x9d",
640
		"\xc2\x94" => "\xe2\x80\x9d",
640
		"\xc2\x95" => "\xe2\x80\xa2",
641
		"\xc2\x95" => "\xe2\x80\xa2",
641
		"\xc2\x96" => "\xe2\x80\x93",
642
		"\xc2\x96" => "\xe2\x80\x93",
642
		"\xc2\x97" => "\xe2\x80\x94",
643
		"\xc2\x97" => "\xe2\x80\x94",
643
		
644
		
644
		"\xc2\x98" => "\xcb\x9c",
645
		"\xc2\x98" => "\xcb\x9c",
645
		"\xc2\x99" => "\xe2\x84\xa2",
646
		"\xc2\x99" => "\xe2\x84\xa2",
646
		"\xc2\x9a" => "\xc5\xa1",
647
		"\xc2\x9a" => "\xc5\xa1",
647
		"\xc2\x9b" => "\xe2\x80\xba",
648
		"\xc2\x9b" => "\xe2\x80\xba",
648
		"\xc2\x9c" => "\xc5\x93",
649
		"\xc2\x9c" => "\xc5\x93",
649
		"\xc2\x9e" => "\xc5\xbe",
650
		"\xc2\x9e" => "\xc5\xbe",
650
		"\xc2\x9f" => "\xc5\xb8"
651
		"\xc2\x9f" => "\xc5\xb8"
651
	);
652
	);
652
	return strtr(utf8_encode($str), $cp1252_map);
653
	return strtr(utf8_encode($str), $cp1252_map);
653
}
654
}
654
?>
655
?>