Remove Address::updateGeocoding unused parameter
[platal.git] / classes / address.php
CommitLineData
eb54852e
SJ
1<?php
2/***************************************************************************
c441aabe 3 * Copyright (C) 2003-2014 Polytechnique.org *
eb54852e
SJ
4 * http://opensource.polytechnique.org/ *
5 * *
6 * This program is free software; you can redistribute it and/or modify *
7 * it under the terms of the GNU General Public License as published by *
8 * the Free Software Foundation; either version 2 of the License, or *
9 * (at your option) any later version. *
10 * *
11 * This program is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU General Public License *
17 * along with this program; if not, write to the Free Software *
18 * Foundation, Inc., *
19 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
20 ***************************************************************************/
21
22/** Class Address is meant to perform most of the access to the table profile_addresses.
23 *
24 * profile_addresses describes an Address, which can be related to either a
25 * Profile, a Job or a Company:
26 * - for a Profile:
27 * - `type` is set to 'home'
28 * - `pid` is set to the related profile pid (in profiles)
29 * - `id` is the id of the address in the list of those related to that profile
30 * - `jobid` is set to 0
31 *
32 * - for a Company:
33 * - `type` is set to 'hq'
34 * - `pid` is set to 0
35 * - `jobid` is set to the id of the company (in profile_job_enum)
36 * - `id` is set to 0 (only one address per Company)
37 *
38 * - for a Job:
39 * - `type` is set to 'job'
40 * - `pid` is set to the pid of the Profile of the related Job (in both profiles and profile_job)
41 * - `id` is the id of the job to which we refer (in profile_job)
42 * - `jobid` is set to 0
43 *
baab50c7
SJ
44 * - for a Group:
45 * - `type` is set to 'group'
46 * - `pid` is set to 0
47 * - `jobid` is set to 0
48 * - `groupid` is set to the group id
49 *
eb54852e
SJ
50 * Thus an Address can be linked to a Company, a Profile, or a Job.
51 */
52class Address
53{
54 const LINK_JOB = 'job';
55 const LINK_COMPANY = 'hq';
56 const LINK_PROFILE = 'home';
baab50c7 57 const LINK_GROUP = 'group';
eb54852e 58
f5f68e07
SJ
59 // List of all available postal formattings.
60 private static $formattings = array('FRANCE' => 'FR');
61
62 // Abbreviations to be used to format French postal addresses.
63 private static $streetAbbreviations = array(
64 'ALLEE' => 'ALL',
65 'AVENUE' => 'AV',
66 'BOULEVARD' => 'BD',
67 'CENTRE' => 'CTRE',
68 'CENTRE COMMERCIAL' => 'CCAL',
69 'IMMEUBLE' => 'IMM',
70 'IMMEUBLES' => 'IMM',
71 'IMPASSE' => 'IMP',
72 'LIEU-DIT' => 'LD',
73 'LOTISSEMENT' => 'LOT',
74 'PASSAGE' => 'PAS',
75 'PLACE' => 'PL',
76 'RESIDENCE' => 'RES',
77 'ROND-POINT' => 'RPT',
78 'ROUTE' => 'RTE',
79 'SQUARE' => 'SQ',
80 'VILLAGE' => 'VLGE',
81 'ZONE D\'ACTIVITE' => 'ZA',
82 'ZONE D\'AMENAGEMENT CONCERTE' => 'ZAC',
83 'ZONE D\'AMENAGEMENT DIFFERE' => 'ZAD',
84 'ZONE INDUSTRIELLE' => 'ZI'
85 );
86 private static $otherAbbreviations = array(
87 'ADJUDANT' => 'ADJ',
88 'AERODROME' => 'AERD',
89 'AEROGARE' => 'AERG',
90 'AERONAUTIQUE' => 'AERN',
91 'AEROPORT' => 'AERP',
92 'AGENCE' => 'AGCE',
93 'AGRICOLE' => 'AGRIC',
94 'ANCIEN' => 'ANC',
95 'ANCIENNEMENT' => 'ANC',
96 'APPARTEMENT' => 'APP',
97 'APPARTEMENTS' => 'APP',
98 'ARMEMENT' => 'ARMT',
99 'ARRONDISSEMENT' => 'ARR',
100 'ASPIRANT' => 'ASP',
101 'ASSOCIATION' => 'ASSOC',
102 'ASSURANCE' => 'ASSUR',
103 'ATELIER' => 'AT',
104 'BARAQUEMENT' => 'BRQ',
105 'BAS' => 'BAS',
106 'BASSE' => 'BAS',
107 'BASSES' => 'BAS',
108 'BATAILLON' => 'BTN',
109 'BATAILLONS' => 'BTN',
110 'BATIMENT' => 'BAT',
111 'BATIMENTS' => 'BAT',
112 'BIS' => 'B',
113 'BOITE POSTALE' => 'BP',
114 'CABINET' => 'CAB',
115 'CANTON' => 'CANT',
116 'CARDINAL' => 'CDL',
117 'CASE POSTALE' => 'CP',
118 'CHAMBRE' => 'CHBR',
119 'CITADELLE' => 'CTD',
120 'COLLEGE' => 'COLL',
121 'COLONEL' => 'CNL',
122 'COLONIE' => 'COLO',
123 'COMITE' => 'CTE',
124 'COMMANDANT' => 'CDT',
125 'COMMERCIAL' => 'CIAL',
126 'COMMUNE' => 'COM',
127 'COMMUNAL' => 'COM',
128 'COMMUNAUX' => 'COM',
129 'COMPAGNIE' => 'CIE',
130 'COMPAGNON' => 'COMP',
131 'COMPAGNONS' => 'COMP',
132 'COOPERATIVE' => 'COOP',
133 'COURSE SPECIALE' => 'CS',
134 'CROIX' => 'CRX',
135 'DELEGATION' => 'DELEG',
136 'DEPARTEMENTAL' => 'DEP',
137 'DEPARTEMENTAUX' => 'DEP',
138 'DIRECTEUR' => 'DIR',
139 'DIRECTECTION' => 'DIR',
140 'DIVISION' => 'DIV',
141 'DOCTEUR' => 'DR',
142 'ECONOMIE' => 'ECO',
143 'ECONOMIQUE' => 'ECO',
144 'ECRIVAIN' => 'ECRIV',
145 'ECRIVAINS' => 'ECRIV',
146 'ENSEIGNEMENT' => 'ENST',
147 'ENSEMBLE' => 'ENS',
148 'ENTREE' => 'ENT',
149 'ENTREES' => 'ENT',
150 'ENTREPRISE' => 'ENTR',
151 'EPOUX' => 'EP',
152 'EPOUSE' => 'EP',
153 'ETABLISSEMENT' => 'ETS',
154 'ETAGE' => 'ETG',
155 'ETAT MAJOR' => 'EM',
156 'EVEQUE' => 'EVQ',
157 'FACULTE' => 'FAC',
158 'FORET' => 'FOR',
159 'FORESTIER' => 'FOR',
160 'FRANCAIS' => 'FR',
161 'FRANCAISE' => 'FR',
162 'FUSILIER' => 'FUS',
163 'GENDARMERIE' => 'GEND',
164 'GENERAL' => 'GAL',
165 'GOUVERNEMENTAL' => 'GOUV',
166 'GOUVERNEUR' => 'GOU',
167 'GRAND' => 'GD',
168 'GRANDE' => 'GDE',
169 'GRANDES' => 'GDES',
170 'GRANDS' => 'GDS',
171 'HAUT' => 'HT',
172 'HAUTE' => 'HTE',
173 'HAUTES' => 'HTES',
174 'HAUTS' => 'HTS',
175 'HOPITAL' => 'HOP',
176 'HOPITAUX' => 'HOP',
177 'HOSPICE' => 'HOSP',
178 'HOSPITALIER' => 'HOSP',
179 'HOTEL' => 'HOT',
180 'INFANTERIE' => 'INFANT',
181 'INFERIEUR' => 'INF',
182 'INFERIEUR' => 'INF',
183 'INGENIEUR' => 'ING',
184 'INSPECTEUR' => 'INSP',
185 'INSTITUT' => 'INST',
186 'INTERNATIONAL' => 'INTERN',
187 'INTERNATIONALE' => 'INTERN',
188 'LABORATOIRE' => 'LABO',
189 'LIEUTENANT' => 'LT',
190 'LIEUTENANT DE VAISSEAU' => 'LTDV',
191 'MADAME' => 'MME',
192 'MADEMOISELLE' => 'MLLE',
193 'MAGASIN' => 'MAG',
194 'MAISON' => 'MAIS',
195 'MAITRE' => 'ME',
196 'MARECHAL' => 'MAL',
197 'MARITIME' => 'MAR',
198 'MEDECIN' => 'MED',
199 'MEDICAL' => 'MED',
200 'MESDAMES' => 'MMES',
201 'MESDEMOISELLES' => 'MLLES',
202 'MESSIEURS' => 'MM',
203 'MILITAIRE' => 'MIL',
204 'MINISTERE' => 'MIN',
205 'MONSEIGNEUR' => 'MGR',
206 'MONSIEUR' => 'M',
207 'MUNICIPAL' => 'MUN',
208 'MUTUEL' => 'MUT',
209 'NATIONAL' => 'NAL',
210 'NOTRE DAME' => 'ND',
211 'NOUVEAU' => 'NOUV',
212 'NOUVEL' => 'NOUV',
213 'NOUVELLE' => 'NOUV',
214 'OBSERVATOIRE' => 'OBS',
215 'PASTEUR' => 'PAST',
216 'PETIT' => 'PT',
217 'PETITE' => 'PTE',
218 'PETITES' => 'PTES',
219 'PETITS' => 'PTS',
220 'POLICE' => 'POL',
221 'PREFET' => 'PREF',
222 'PREFECTURE' => 'PREF',
223 'PRESIDENT' => 'PDT',
224 'PROFESSEUR' => 'PR',
225 'PROFESSIONNEL' => 'PROF',
226 'PROFESSIONNELE' => 'PROF',
227 'PROLONGE' => 'PROL',
228 'PROLONGEE' => 'PROL',
229 'PROPRIETE' => 'PROP',
230 'QUATER' => 'Q',
231 'QUINQUIES' => 'C',
232 'RECTEUR' => 'RECT',
233 'REGIMENT' => 'RGT',
234 'REGION' => 'REG',
235 'REGIONAL' => 'REG',
236 'REGIONALE' => 'REG',
237 'REPUBLIQUE' => 'REP',
238 'RESTAURANT' => 'REST',
239 'SAINT' => 'ST',
240 'SAINTE' => 'STE',
241 'SAINTES' => 'STES',
242 'SAINTS' => 'STS',
243 'SANATORIUM' => 'SANA',
244 'SERGENT' => 'SGT',
245 'SERVICE' => 'SCE',
246 'SOCIETE' => 'SOC',
247 'SOUS COUVERT' => 'SC',
248 'SOUS-PREFET' => 'SPREF',
249 'SUPERIEUR' => 'SUP',
250 'SUPERIEURE' => 'SUP',
251 'SYNDICAT' => 'SYND',
252 'TECHNICIEN' => 'TECH',
253 'TECHNICIENNE' => 'TECH',
254 'TECHNICIQUE' => 'TECH',
255 'TER' => 'T',
256 'TRI SERVICE ARRIVEE' => 'TSA',
257 'TUNNEL' => 'TUN',
258 'UNIVERSITAIRE' => 'UNVT',
259 'UNIVERSITE' => 'UNIV',
260 'VELODROME' => 'VELOD',
261 'VEUVE' => 'VVE',
262 'VIEILLE' => 'VIEL',
263 'VIEILLES' => 'VIEL',
264 'VIEUX' => 'VX'
265 );
266 private static $entrepriseAbbreviations = array(
267 'COOPERATIVE D\'UTILISATION DE MATERIEL AGRICOLE EN COMMUN' => 'CUMA',
268 'ETABLISSEMENT PUBLIC A CARACTERE INDUSTRIEL ET COMMERCIAL' => 'EPIC',
269 'ETABLISSEMENT PUBLIC ADMINISTRATIF' => 'EPA',
270 'GROUPEMENT AGRICOLE D\'EXPLOITATION EN COMMUN' => 'GAEC',
271 'GROUPEMENT D\'INTERET ECONOMIQUE' => 'GIE',
272 'GROUPEMENT D\'INTERET PUBLIC' => 'GIP',
273 'GROUPEMENT EUROPEEN D\'INTERET ECONOMIQUE' => 'GEIE',
274 'OFFICE PUBLIC D\'HABITATION A LOYER MODERE' => 'OPHLM',
275 'SOCIETE A RESPONSABILITE LIMITEE' => 'SARL',
276 'SOCIETE ANONYME' => 'SA',
277 'SOCIETE CIVILE DE PLACEMENT COLLECTIF IMMOBILIER' => 'SCPI',
278 'SOCIETE CIVILE PROFESSIONNELLE' => 'SCP',
279 'SOCIETE COOPERATIVE OUVRIERE DE PRODUCTION ET DE CREDIT' => 'SCOP',
280 'SOCIETE D\'AMENAGEMENT FONCIER ET D\'EQUIPEMENT RURAL' => 'SAFER',
281 'SOCIETE D\'ECONOMIE MIXTE' => 'SEM',
282 'SOCIETE D\'INTERET COLLECTIF AGRICOLE' => 'SICA',
283 'SOCIETE D\'INVESTISSEMENT A CAPITAL VARIABLE' => 'SICAV',
284 'SOCIETE EN NOM COLLECTIF' => 'SNC',
285 'SOCIETE IMMOBILIERE POUR LE COMMERCE ET L\'INDUSTRIE' => 'SICOMI',
286 'SOCIETE MIXTE D\'INTERET AGRICOLE' => 'SMIA',
287 'SYNDICAT INTERCOMMUNAL A VOCATION MULTIPLE' => 'SIVOM',
288 'SYNDICAT INTERCOMMUNAL A VOCATION UNIQUE' => 'SIVU'
289 );
290
eb54852e
SJ
291 // Primary key fields: the quadruplet ($pid, $jobid, $type, $id) defines a unique address.
292 public $pid = 0;
293 public $jobid = 0;
baab50c7 294 public $groupid = 0;
eb54852e
SJ
295 public $type = Address::LINK_PROFILE;
296 public $id = 0;
297
298 // Geocoding fields.
eb54852e
SJ
299 public $text = '';
300 public $postalText = '';
e44d8688 301 public $postal_code_fr = null;
0f5f1b70
SJ
302 public $types = '';
303 public $formatted_address = '';
304 public $components = array();
eb54852e
SJ
305 public $latitude = null;
306 public $longitude = null;
0f5f1b70
SJ
307 public $southwest_latitude = null;
308 public $southwest_longitude = null;
309 public $northeast_latitude = null;
310 public $northeast_longitude = null;
311 public $location_type = '';
312 public $partial_match = false;
313 public $componentsIds = '';
57fa97b3 314 public $request = false;
72a4c6a8
SJ
315 public $geocoding_date = null;
316 public $geocoding_calls = 0;
eb54852e
SJ
317
318 // Database's field required for both 'home' and 'job' addresses.
5f096c57 319 public $pub = 'ax';
eb54852e
SJ
320
321 // Database's fields required for 'home' addresses.
baee0f5a 322 public $flags = null; // 'current', 'temporary', 'secondary', 'mail', 'cedex', 'deliveryIssue'
eb54852e
SJ
323 public $comment = null;
324 public $current = null;
325 public $temporary = null;
326 public $secondary = null;
327 public $mail = null;
baee0f5a 328 public $deliveryIssue = null;
eb54852e
SJ
329
330 // Remaining fields that do not belong to profile_addresses.
331 public $phones = array();
332 public $error = false;
333 public $changed = 0;
334 public $removed = 0;
335
336 public function __construct(array $data = array())
337 {
338 if (count($data) > 0) {
339 foreach ($data as $key => $val) {
340 $this->$key = $val;
341 }
342 }
343
545bc699
FB
344 if (!is_null($this->flags)) {
345 $this->flags = new PlFlagSet($this->flags);
346 } else {
baee0f5a 347 static $flags = array('current', 'temporary', 'secondary', 'mail', 'deliveryIssue');
eb54852e 348
545bc699
FB
349 $this->flags = new PlFlagSet();
350 foreach ($flags as $flag) {
351 if (!is_null($this->$flag) && ($this->$flag == 1 || $this->$flag == 'on')) {
352 $this->flags->addFlag($flag, 1);
353 $this->$flag = null;
eb54852e 354 }
545bc699
FB
355 $this->flags->addFlag('cedex', (strpos(strtoupper(preg_replace(array("/[0-9,\"'#~:;_\- ]/", "/\r\n/"),
356 array('', "\n"), $this->text)), 'CEDEX')) !== false);
eb54852e
SJ
357 }
358 }
a3328b1e 359 $this->request = ($this->request || !is_null(AddressReq::get_request($this->pid, $this->jobid, $this->groupid, $this->type, $this->id)));
eb54852e
SJ
360 }
361
323ac187
SJ
362 public function setId($id)
363 {
364 $this->id = $id;
365 }
366
eb54852e
SJ
367 public function phones()
368 {
369 return $this->phones;
370 }
371
26ba053e 372 public function addPhone(Phone $phone)
eb54852e 373 {
0b53817f 374 if ($phone->link_type == Phone::LINK_ADDRESS && $phone->pid == $this->pid) {
eb54852e
SJ
375 $this->phones[$phone->uniqueId()] = $phone;
376 }
377 }
378
379 public function hasFlag($flag)
380 {
622e7063 381 return ($this->flags != null && $this->flags->hasFlag($flag));
eb54852e
SJ
382 }
383
24ede2d2
SJ
384 public function addFlag($flag)
385 {
386 $this->flags->addFlag($flag);
387 }
388
f5f68e07
SJ
389 /** Auxilary function for formatting postal addresses.
390 * If the needle is found in the haystack, it notifies the substitution's
391 * success, modifies the length accordingly and returns either the matching
392 * substitution or the needle.
393 */
9070ff05 394 private function substitute($needle, $haystack, &$length, &$success, $trim = false)
f5f68e07
SJ
395 {
396 if (array_key_exists($needle, $haystack)) {
397 $success = true;
398 $length -= (strlen($needle) - strlen($haystack[$needle]));
399 return $haystack[$needle];
9070ff05
SJ
400 } elseif ($trim) {
401 $success = true;
402 if (strlen($needle) > 4) {
403 $length -= (strlen($needle) - 4);
404 $needle = $needle{4};
405 }
f5f68e07
SJ
406 }
407 return $needle;
408 }
409
410 /** Checks if the line corresponds to a French street line.
411 * A line is considered a French street line if it starts by between 1 and 4 numbers.
412 */
413 private function isStreetFR($line)
414 {
415 return preg_match('/^\d{1,4}\D/', $line);
416 }
417
418 /** Retrieves a French street number and slit the rest of the line into an array.
419 * @param $words: array containing the rest of the line (a word per cell).
420 * @param $line: line to consider.
421 * Returns the street number.
422 */
423 private function getStreetNumberFR(&$line)
424 {
425 // First we define numbers and separators.
426 $numberReq = '(\d{1,4})\s*(BIS|TER|QUATER|[A-Z])?';
292c2b3e 427 $separatorReq = '\s*(?:\\\\|\/|-|&|A|ET)?\s*';
cce807c5
SJ
428
429 // Then we retrieve the number(s) and the rest of the line.
430 // $matches contains:
431 // -0: the full patern, here the given line,
432 // -1: the number,
433 // -2: its optionnal quantifier,
434 // -3: an optionnal second number,
435 // -4: the second number's optionnal quantifier,
436 // -5: the rest of the line.
437 preg_match('/^' . $numberReq . '(?:' . $separatorReq . $numberReq . ')?\s+(.*)/', $line, $matches);
f5f68e07
SJ
438 $number = $matches[1];
439 $line = $matches[5];
440
441 // If there is a precision on the address, we concatenate it to the number.
442 if ($matches[2] != '') {
cce807c5 443 $number .= $matches[2]{0};
f5f68e07 444 } elseif ($matches[4] != '') {
cce807c5 445 $number .= $matches[4]{0};
f5f68e07
SJ
446 }
447
448 return $number;
449 }
450
451 /** Checks if the line corresponds to a French locality line.
452 * A line is considered a French locality line if it starts by exactly a
453 * postal code of exactly 5 numbers.
454 */
455 private function isLocalityFR($line)
456 {
457 return preg_match('/^\d{5}\D/', $line);
458 }
459
460 /** Retrieves a French postal code and slit the rest of the line into an array.
461 * @param $words: array containing the rest of the line (a word per cell).
462 * @param $line: line to consider.
463 * Returns the postal code, and cuts it out from the line.
464 */
465 private function getPostalCodeFR(&$line)
466 {
467 $number = substr($line, 0, 5);
468 $line = trim(substr($line, 5));
469 return $number;
470 }
471
472 /** Returns the address formated for French postal use (cf AFNOR XPZ 10-011).
473 * A postal addresse containts at most 6 lines of at most 38 characters each:
474 * - addressee's identification ("MONSIEUR JEAN DURAND", "DURAND SA"…),
475 * - delivery point identification ("CHEZ TOTO APPARTEMENT 2", "SERVICE ACHAT"…),
476 * - building localisation complement ("ENTREE A BATIMENT DES JONQUILLES", "ZONE INDUSTRIELLE OUEST"…),
477 * - N° and street name ("25 RUE DES FLEURS", "LES VIGNES"…),
478 * - delivery service, street localisation complement ("BP 40122", "BP 40112 AREYRES"…),
479 * - postal code and locality or cedex code and cedex ("33500 LIBOURNE", "33506 LIBOURNE CEDEX"…).
480 * Punctuation must be removed, all leters must be uppercased.
481 * Both locality and street name must not take more than 32 characters.
482 *
483 * @param $arrayText: array containing the address to be formated, one
484 * address line per array line.
485 * @param $count: array size.
486 */
cce807c5 487 private function formatPostalAddressFR($arrayText)
f5f68e07
SJ
488 {
489 // First removes country if any.
cce807c5 490 $count = count($arrayText);
f5f68e07
SJ
491 if ($arrayText[$count - 1] == 'FRANCE') {
492 unset($arrayText[$count - 1]);
493 --$count;
494 }
495
e44d8688 496 $postal_code = null;
f5f68e07
SJ
497 // All the lines must have less than 38 characters but street and
498 // locality lines whose limit is 32 characters.
499 foreach ($arrayText as $lineNumber => $line) {
500 if ($isStreetLine = $this->isStreetFR($line)) {
501 $formattedLine = $this->getStreetNumberFR($line) . ' ';
502 $limit = 32;
503 } elseif ($this->isLocalityFR($line)) {
e44d8688
SJ
504 $postal_code = $this->getPostalCodeFR($line);
505 $formattedLine = $postal_code . ' ';
f5f68e07 506 $limit = 32;
59e8fb00 507 } else {
f5f68e07
SJ
508 $formattedLine = '';
509 $limit = 38;
510 }
511
512 $words = explode(' ', $line);
513 $count = count($words);
514 $length = $count - 1;
515 foreach ($words as $word) {
516 $length += strlen($word);
59e8fb00 517 }
f5f68e07
SJ
518
519 // Checks is length is ok. Otherwise, we try to shorten words and
520 // update the length of the current line accordingly.
521 for ($i = 0; $i < $count && $length > $limit; ++$i) {
522 $success = false;
523 if ($isStreetLine) {
9070ff05 524 $sub = $this->substitute($words[$i], Address::$streetAbbreviations, $length, $success, ($i == 0));
f5f68e07
SJ
525 }
526 // Entreprises' substitution are only suitable for the first two lines.
527 if ($lineNumber <= 2 && !$success) {
528 $sub = $this->substitute($words[$i], Address::$entrepriseAbbreviations, $length, $success);
529 }
530 if (!$success) {
531 $sub = $this->substitute($words[$i], Address::$otherAbbreviations, $length, $success);
532 }
533
534 $formattedLine .= $sub . ' ';
535 }
536 for (; $i < $count; ++$i) {
537 $formattedLine .= $words[$i] . ' ';
538 }
539 $arrayText[$lineNumber] = trim($formattedLine);
59e8fb00 540 }
f5f68e07 541
e44d8688 542 $this->postal_code_fr = $postal_code;
f5f68e07
SJ
543 return implode("\n", $arrayText);
544 }
545
546 // Formats postal addresses.
547 // First erases punctuation, accents… Then uppercase the address and finally
548 // calls the country's dedicated formatting function.
549 public function formatPostalAddress()
550 {
551 // Performs rough formatting.
552 $text = mb_strtoupper(replace_accent($this->text));
553 $text = str_replace(array(',', ';', '.', ':', '!', '?', '"', '«', '»'), '', $text);
554 $text = preg_replace('/( |\t)+/', ' ', $text);
555 $arrayText = explode("\n", $text);
556 $arrayText = array_map('trim', $arrayText);
557
928c303e
SJ
558 // Formats according to country rules. Thus we first identify the
559 // country, then apply corresponding formatting or translate country
560 // into default language.
f5f68e07 561 $count = count($arrayText);
0f5f1b70
SJ
562 list($countryId, $country) = XDB::fetchOneRow('SELECT gc.iso_3166_1_a2, gc.country
563 FROM geoloc_countries AS gc
564 INNER JOIN geoloc_languages AS gl ON (gc.iso_3166_1_a2 = gl.iso_3166_1_a2)
565 WHERE gl.countryPlain = {?} OR gc.countryPlain = {?}',
566 $arrayText[$count - 1], $arrayText[$count - 1]);
567 if (is_null($countryId)) {
568 $text = $this->formatPostalAddressFR($arrayText);
569 } elseif (in_array(strtoupper($countryId), Address::$formattings)) {
570 $text = call_user_func(array($this, 'formatPostalAddress' . strtoupper($countryId)), $arrayText);
f5f68e07 571 } else {
0f5f1b70
SJ
572 $arrayText[$count - 1] = mb_strtoupper(replace_accent($country));
573 $text = implode("\n", $arrayText);
f5f68e07
SJ
574 }
575
576 $this->postalText = $text;
59e8fb00
SJ
577 }
578
00b2bc89 579 public function format()
eb54852e 580 {
eb54852e 581 $this->text = trim($this->text);
22771578 582 $this->phones = Phone::formatFormArray($this->phones, $this->error, $this->pub);
eb54852e 583 if ($this->removed == 1) {
0409b3c2 584 if (!S::user()->checkPerms('directory_private') && Phone::hasPrivate($this->phones)) {
0c1a29ba
SJ
585 Platal::page()->trigWarning("L'adresse ne peut être supprimée car elle contient des informations pour lesquelles vous n'avez le droit d'édition.");
586 } else {
587 $this->text = '';
588 return true;
589 }
eb54852e
SJ
590 }
591
00b2bc89
SJ
592 $this->formatPostalAddress();
593 if ($this->changed == 1) {
eb54852e
SJ
594 $gmapsGeocoder = new GMapsGeocoder();
595 $gmapsGeocoder->getGeocodedAddress($this);
0f5f1b70 596
a3328b1e
SJ
597 $componants = array();
598 foreach ($this->components as $component) {
599 $componants[] = Geocoder::getComponentId($component);
600 }
601 $this->componentsIds = implode(',', $componants);
f2ac8f49 602 }
99d55045
SJ
603 if ($this->componentsIds == '') {
604 $this->latitude = null;
605 $this->longitude = null;
606 }
00b2bc89
SJ
607
608 return true;
eb54852e
SJ
609 }
610
611 public function toFormArray()
612 {
613 $address = array(
0f5f1b70
SJ
614 'text' => $this->text,
615 'postalText' => $this->postalText,
616 'types' => $this->types,
617 'formatted_address' => $this->formatted_address,
618 'latitude' => $this->latitude,
619 'longitude' => $this->longitude,
620 'southwest_latitude' => $this->southwest_latitude,
621 'southwest_longitude' => $this->southwest_longitude,
622 'northeast_latitude' => $this->northeast_latitude,
623 'northeast_longitude' => $this->northeast_longitude,
624 'location_type' => $this->location_type,
625 'partial_match' => $this->partial_match,
57fa97b3 626 'componentsIds' => $this->componentsIds,
72a4c6a8
SJ
627 'geocoding_date' => $this->geocoding_date,
628 'geocoding_calls' => $this->geocoding_calls,
57fa97b3 629 'request' => $this->request
eb54852e 630 );
eb54852e 631
ddc383d5
SJ
632 if ($this->type == self::LINK_JOB) {
633 $address['pub'] = $this->pub;
634 $address['mail'] = $this->flags->hasFlag('mail');
eb54852e
SJ
635 }
636 if ($this->type == self::LINK_PROFILE) {
baee0f5a 637 static $flags = array('current', 'temporary', 'secondary', 'mail', 'cedex', 'deliveryIssue');
eb54852e
SJ
638 foreach ($flags as $flag) {
639 $address[$flag] = $this->flags->hasFlag($flag);
640 }
ddc383d5 641 $address['pub'] = $this->pub;
eb54852e
SJ
642 $address['comment'] = $this->comment;
643 $address['phones'] = Phone::formatFormArray($this->phones);
644 }
645
646 return $address;
647 }
648
649 private function toString()
650 {
14aba233 651 $address = $this->text;
eb54852e 652 if ($this->type == self::LINK_PROFILE || $this->type == self::LINK_JOB) {
b49e98ca 653 static $pubs = array('public' => 'publique', 'ax' => 'annuaire papier', 'private' => 'privé', 'hidden' => 'administrateurs');
14aba233 654 $address .= ' (affichage ' . $pubs[$this->pub];
eb54852e
SJ
655 }
656 if ($this->type == self::LINK_PROFILE) {
657 static $flags = array(
baee0f5a
SJ
658 'current' => 'actuelle',
659 'temporary' => 'temporaire',
660 'secondary' => 'secondaire',
661 'mail' => 'conctactable par courier',
662 'deliveryIssue' => 'n\'habite pas à l\'adresse indiquée',
663 'cedex' => 'type cédex',
eb54852e
SJ
664 );
665
14aba233
SJ
666 if (!$this->flags->hasFlag('temporary')) {
667 $address .= ', permanente';
668 }
669 if (!$this->flags->hasFlag('secondary')) {
670 $address .= ', principale';
671 }
eb54852e
SJ
672 foreach ($flags as $flag => $flagName) {
673 if ($this->flags->hasFlag($flag)) {
674 $address .= ', ' . $flagName;
675 }
676 }
14aba233
SJ
677 if ($this->comment) {
678 $address .= ', commentaire : ' . $this->comment;
679 }
eb54852e
SJ
680 if ($phones = Phone::formArrayToString($this->phones)) {
681 $address .= ', ' . $phones;
682 }
14aba233
SJ
683 } elseif ($this->type == self::LINK_JOB) {
684 $address .= ')';
eb54852e
SJ
685 }
686 return $address;
687 }
688
689 private function isEmpty()
690 {
691 return (!$this->text || $this->text == '');
692 }
693
3f96e56b 694 public function save($notify_ungeocoded = true)
eb54852e 695 {
eb54852e 696 if (!$this->isEmpty()) {
0f5f1b70
SJ
697 XDB::execute('INSERT IGNORE INTO profile_addresses (pid, jobid, groupid, type, id, flags, text, postalText, pub, comment,
698 types, formatted_address, location_type, partial_match, latitude, longitude,
72a4c6a8 699 southwest_latitude, southwest_longitude, northeast_latitude, northeast_longitude,
e44d8688 700 geocoding_date, geocoding_calls, postal_code_fr)
0f5f1b70 701 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?},
e44d8688 702 {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, NOW(), {?}, {?})',
0f5f1b70
SJ
703 $this->pid, $this->jobid, $this->groupid, $this->type, $this->id, $this->flags, $this->text, $this->postalText, $this->pub, $this->comment,
704 $this->types, $this->formatted_address, $this->location_type, $this->partial_match, $this->latitude, $this->longitude,
e44d8688 705 $this->southwest_latitude, $this->southwest_longitude, $this->northeast_latitude, $this->northeast_longitude, $this->geocoding_calls, $this->postal_code_fr);
0f5f1b70
SJ
706
707 if ($this->componentsIds) {
708 foreach (explode(',', $this->componentsIds) as $component_id) {
709 XDB::execute('INSERT IGNORE INTO profile_addresses_components (pid, jobid, groupid, type, id, component_id)
710 VALUES ({?}, {?}, {?}, {?}, {?}, {?})',
711 $this->pid, $this->jobid, $this->groupid, $this->type, $this->id, $component_id);
712 }
3f96e56b 713 } elseif ($notify_ungeocoded) {
41f4556b
SJ
714 // If the address was not geocoded, notifies it to the appropriate ML.
715 $mailer = new PlMailer('profile/no_geocoding.mail.tpl');
716 $mailer->assign('text', $this->text);
717 $mailer->assign('primary_key', $this->pid . '-' . $this->jobid . '-' . $this->groupid . '-' . $this->type . '-' . $this->id);
718 $mailer->send();
0f5f1b70 719 }
eb54852e
SJ
720
721 if ($this->type == self::LINK_PROFILE) {
722 Phone::savePhones($this->phones, $this->pid, Phone::LINK_ADDRESS, $this->id);
723 }
a3328b1e
SJ
724
725 if ($this->request) {
726 $req = new AddressReq(S::user(), $this->toFormArray(), $this->pid, $this->jobid, $this->groupid, $this->type, $this->id);
727 $req->submit();
728 }
f75a1212
SJ
729
730 if ($this->pid != 0) {
c0c966f5 731 self::updateBestMail($this->pid);
f75a1212
SJ
732 }
733 }
734 }
735
8a1f4fbf
NI
736 /**
737 * Upate the denormalized flag which is used to mark the best mail to use
738 * when sending postal mail
c0c966f5
NI
739 *
740 * Call with $fake to true to only get which address would be selected,
741 * without updating anything in the database.
742 * Returns an array describing the selected profile address
8a1f4fbf 743 */
c0c966f5 744 static public function updateBestMail($pid, $fake=false)
f75a1212 745 {
c0c966f5
NI
746 if (!$fake) {
747 XDB::execute("UPDATE profile_addresses
748 SET flags = REPLACE(flags, 'dn_best_mail', '')
749 WHERE pid = {?}",
750 $pid);
751 }
f75a1212 752
8a1f4fbf
NI
753 /* Following order is selected to find the best mail:
754 * * Use addresses without the deliveryIssue flag if possible.
755 * * Among these, use addresses flagged as "current".
756 * * If there is no such addresses or several ones, prefer those
757 * without "secondary" flag.
758 * * If there are still several addresses in the selection, try not
759 * to select the ones with "job" type.
760 */
c0c966f5 761 $best_mail = XDB::fetchOneAssoc("SELECT pid, jobid, groupid, type, id, flags
f75a1212 762 FROM profile_addresses
8a1f4fbf 763 WHERE FIND_IN_SET('mail', flags) AND pid = {?}
821ec024
NI
764 ORDER BY FIND_IN_SET('deliveryIssue', flags),
765 NOT FIND_IN_SET('current', flags),
8a1f4fbf
NI
766 FIND_IN_SET('secondary', flags), type = 'job'
767 LIMIT 1",
c0c966f5 768 $pid);
f75a1212 769
c0c966f5 770 if (!$fake && $best_mail) {
f75a1212 771 XDB::execute("UPDATE profile_addresses
8a1f4fbf 772 SET flags = CONCAT(flags, ',dn_best_mail')
f75a1212 773 WHERE pid = {?} AND jobid = {?} AND groupid = {?} AND type = {?} AND id = {?}",
8a1f4fbf 774 $best_mail['pid'], $best_mail['jobid'], $best_mail['groupid'], $best_mail['type'], $best_mail['id']);
eb54852e 775 }
c0c966f5 776 return $best_mail;
eb54852e
SJ
777 }
778
8526cfe0 779 public function updateGeocoding()
57fa97b3 780 {
a3328b1e
SJ
781 XDB::execute('UPDATE profile_addresses
782 SET text = {?}, postalText = {?}, types = {?}, formatted_address = {?},
783 location_type = {?}, partial_match = {?}, latitude = {?}, longitude = {?},
784 southwest_latitude = {?}, southwest_longitude = {?}, northeast_latitude = {?}, northeast_longitude = {?},
785 geocoding_date = NOW(), geocoding_calls = {?}
786 WHERE pid = {?} AND jobid = {?} AND groupid = {?} AND type = {?} AND id = {?}',
787 $this->text, $this->postalText, $this->types, $this->formatted_address,
788 $this->location_type, $this->partial_match, $this->latitude, $this->longitude,
789 $this->southwest_latitude, $this->southwest_longitude, $this->northeast_latitude, $this->northeast_longitude, $this->geocoding_calls,
790 $this->pid, $this->jobid, $this->groupid, $this->type, $this->id);
791
792 XDB::execute('DELETE FROM profile_addresses_components
793 WHERE pid = {?} AND jobid = {?} AND groupid = {?} AND type = {?} AND id = {?}',
794 $this->pid, $this->jobid, $this->groupid, $this->type, $this->id);
795 if ($this->componentsIds) {
796 foreach (explode(',', $this->componentsIds) as $component_id) {
797 XDB::execute('INSERT IGNORE INTO profile_addresses_components (pid, jobid, groupid, type, id, component_id)
798 VALUES ({?}, {?}, {?}, {?}, {?}, {?})',
799 $this->pid, $this->jobid, $this->groupid, $this->type, $this->id, $component_id);
57fa97b3
SJ
800 }
801 }
802 }
803
781a24bc
SJ
804 public function delete()
805 {
02228cb2
SJ
806 XDB::execute('DELETE FROM profile_addresses_components
807 WHERE pid = {?} AND jobid = {?} AND groupid = {?} AND type = {?} AND id = {?}',
808 $this->pid, $this->jobid, $this->groupid, $this->type, $this->id);
781a24bc 809 XDB::execute('DELETE FROM profile_addresses
baab50c7
SJ
810 WHERE pid = {?} AND jobid = {?} AND groupid = {?} AND type = {?} AND id = {?}',
811 $this->pid, $this->jobid, $this->groupid, $this->type, $this->id);
02228cb2
SJ
812
813 return XDB::affectedRows();
781a24bc
SJ
814 }
815
baab50c7 816 static public function deleteAddresses($pid, $type, $jobid = null, $groupid = null, $deletePrivate = true)
eb54852e
SJ
817 {
818 $where = '';
819 if (!is_null($pid)) {
820 $where = XDB::format(' AND pid = {?}', $pid);
821 }
822 if (!is_null($jobid)) {
823 $where = XDB::format(' AND jobid = {?}', $jobid);
824 }
baab50c7
SJ
825 if (!is_null($groupid)) {
826 $where = XDB::format(' AND groupid = {?}', $groupid);
827 }
eb54852e 828 XDB::execute('DELETE FROM profile_addresses
6592a264 829 WHERE type = {?}' . $where . (($deletePrivate) ? '' : ' AND pub IN (\'public\', \'ax\')'),
eb54852e
SJ
830 $type);
831 if ($type == self::LINK_PROFILE) {
6592a264 832 Phone::deletePhones($pid, Phone::LINK_ADDRESS, null, $deletePrivate);
eb54852e
SJ
833 }
834 }
835
836 /** Saves addresses into the database.
837 * @param $data: an array of form formatted addresses.
838 * @param $pid, $type, $linkid: pid, type and id concerned by the update.
839 */
d3ce1117 840 static public function saveFromArray(array $data, $pid, $type = self::LINK_PROFILE, $linkid = null, $savePrivate = true)
eb54852e
SJ
841 {
842 foreach ($data as $id => $value) {
d3ce1117
SJ
843 if ($value['pub'] != 'private' || $savePrivate) {
844 if (!is_null($linkid)) {
845 $value['id'] = $linkid;
846 } else {
847 $value['id'] = $id;
848 }
849 if (!is_null($pid)) {
850 $value['pid'] = $pid;
851 }
852 if (!is_null($type)) {
853 $value['type'] = $type;
854 }
855 $address = new Address($value);
856 $address->save();
eb54852e 857 }
eb54852e
SJ
858 }
859 }
860
861 static private function formArrayWalk(array $data, $function, &$success = true, $requiresEmptyAddress = false)
862 {
863 $addresses = array();
864 foreach ($data as $item) {
865 $address = new Address($item);
866 $success = ($address->format() && $success);
867 if (!$address->isEmpty()) {
868 $addresses[] = call_user_func(array($address, $function));
869 }
870 }
871 if (count($address) == 0 && $requiresEmptyAddress) {
872 $address = new Address();
873 $addresses[] = call_user_func(array($address, $function));
874 }
875 return $addresses;
876 }
877
1f61d10d
SJ
878 // Compares two addresses. First sort by publicity, then place primary
879 // addresses before secondary addresses.
880 static private function compare(array $a, array $b)
881 {
22771578 882 $value = Visibility::comparePublicity($a, $b);
1f61d10d
SJ
883 if ($value == 0) {
884 if ($a['secondary'] != $b['secondary']) {
885 $value = $a['secondary'] ? 1 : -1;
886 }
887 }
888 return $value;
889 }
890
eb54852e
SJ
891 // Formats an array of form addresses into an array of form formatted addresses.
892 static public function formatFormArray(array $data, &$success = true)
893 {
1f61d10d
SJ
894 $addresses = self::formArrayWalk($data, 'toFormArray', $success, true);
895
eb54852e
SJ
896 // Only a single address can be the profile's current address and she must have one.
897 $hasCurrent = false;
1f61d10d 898 foreach ($addresses as $key => &$address) {
eb54852e
SJ
899 if (isset($address['current']) && $address['current']) {
900 if ($hasCurrent) {
901 $address['current'] = false;
902 } else {
903 $hasCurrent = true;
904 }
905 }
906 }
907 if (!$hasCurrent && count($value) > 0) {
908 foreach ($value as &$address) {
909 $address['current'] = true;
910 break;
911 }
912 }
913
1f61d10d 914 usort($addresses, 'Address::compare');
b3d5464e 915 return $addresses;
eb54852e
SJ
916 }
917
918 static public function formArrayToString(array $data)
919 {
14aba233 920 return implode(', ', self::formArrayWalk($data, 'toString'));
eb54852e
SJ
921 }
922
0c1a29ba
SJ
923 static public function hasPrivate(array $addresses)
924 {
925 foreach ($addresses as $address) {
926 if ($address['pub'] == 'private') {
927 return true;
928 }
929 }
930 return false;
931 }
932
eb54852e 933 static public function iterate(array $pids = array(), array $types = array(),
4ea29d3e 934 array $jobids = array(), $visibility = null, $where = null)
eb54852e 935 {
4ea29d3e 936 return new AddressIterator($pids, $types, $jobids, $visibility, $where);
eb54852e
SJ
937 }
938}
939
e4ab8cc8 940/** Iterator over a set of Addresses
eb54852e
SJ
941 *
942 * @param $pid, $type, $jobid, $pub
943 *
e4ab8cc8
NI
944 * The iterator contains the addresses that correspond to the value stored in
945 * the parameters' arrays.
eb54852e
SJ
946 */
947class AddressIterator implements PlIterator
948{
949 private $dbiter;
b9fc85ac 950 private $visibility;
eb54852e 951
4ea29d3e 952 public function __construct(array $pids, array $types, array $jobids, $visibility, $_where)
eb54852e
SJ
953 {
954 $where = array();
4ea29d3e
SJ
955 if (!is_null($_where)) {
956 $where[] = $_where;
957 }
eb54852e
SJ
958 if (count($pids) != 0) {
959 $where[] = XDB::format('(pa.pid IN {?})', $pids);
960 }
961 if (count($types) != 0) {
962 $where[] = XDB::format('(pa.type IN {?})', $types);
963 }
964 if (count($jobids) != 0) {
965 $where[] = XDB::format('(pa.jobid IN {?})', $jobids);
966 }
15b9758d 967 if ($visibility == null || !($visibility instanceof Visibility)) {
22771578 968 $visibility = Visibility::defaultForRead();
eb54852e 969 }
22771578
RB
970 $where[] = 'pve.best_display_level+0 <= pa.pub+0';
971
0f5f1b70
SJ
972 $sql = 'SELECT pa.pid, pa.jobid, pa.groupid, pa.type, pa.id, pa.flags, pa.text, pa.postalText, pa.pub, pa.comment,
973 pa.types, pa.formatted_address, pa.location_type, pa.partial_match, pa.latitude, pa.longitude,
974 pa.southwest_latitude, pa.southwest_longitude, pa.northeast_latitude, pa.northeast_longitude,
72a4c6a8 975 pa.geocoding_date, pa.geocoding_calls,
d9892b2a 976 GROUP_CONCAT(DISTINCT pc.component_id SEPARATOR \',\') AS componentsIds,
07b0a566
SJ
977 GROUP_CONCAT(pace1.long_name) AS postalCode, GROUP_CONCAT(pace2.long_name) AS locality,
978 GROUP_CONCAT(pace3.long_name) AS administrativeArea, GROUP_CONCAT(pace4.long_name) AS country
d9892b2a
SJ
979 FROM profile_addresses AS pa
980 LEFT JOIN profile_addresses_components AS pc ON (pa.pid = pc.pid AND pa.jobid = pc.jobid AND pa.groupid = pc.groupid
981 AND pa.type = pc.type AND pa.id = pc.id)
07b0a566
SJ
982 LEFT JOIN profile_addresses_components_enum AS pace1 ON (FIND_IN_SET(\'postal_code\', pace1.types) AND pace1.id = pc.component_id)
983 LEFT JOIN profile_addresses_components_enum AS pace2 ON (FIND_IN_SET(\'locality\', pace2.types) AND pace2.id = pc.component_id)
984 LEFT JOIN profile_addresses_components_enum AS pace3 ON (FIND_IN_SET(\'administrative_area_level_1\', pace3.types) AND pace3.id = pc.component_id)
985 LEFT JOIN profile_addresses_components_enum AS pace4 ON (FIND_IN_SET(\'country\', pace4.types) AND pace4.id = pc.component_id)
22771578
RB
986 LEFT JOIN profile_visibility_enum AS pve ON (pve.access_level = {?})
987 WHERE ' . implode(' AND ', $where) . '
0f5f1b70 988 GROUP BY pa.pid, pa.jobid, pa.groupid, pa.type, pa.id
eb54852e 989 ORDER BY pa.pid, pa.jobid, pa.id';
22771578 990 $this->dbiter = XDB::iterator($sql, $visibility->level());
b9fc85ac 991 $this->visibility = $visibility;
eb54852e
SJ
992 }
993
994 public function next()
995 {
996 if (is_null($this->dbiter)) {
997 return null;
998 }
999 $data = $this->dbiter->next();
1000 if (is_null($data)) {
1001 return null;
1002 }
1003 // Adds phones to addresses.
b9fc85ac 1004 $it = Phone::iterate(array($data['pid']), array(Phone::LINK_ADDRESS), array($data['id']), $this->visibility);
eb54852e 1005 while ($phone = $it->next()) {
0b53817f 1006 $data['phones'][$phone->id] = $phone->toFormArray();
eb54852e
SJ
1007 }
1008 return new Address($data);
1009 }
1010
1011 public function total()
1012 {
1013 return $this->dbiter->total();
1014 }
1015
1016 public function first()
1017 {
1018 return $this->dbiter->first();
1019 }
1020
1021 public function last()
1022 {
1023 return $this->dbiter->last();
1024 }
1025
1026 public function value()
1027 {
1028 return $this->dbiter;
1029 }
1030}
1031
448c8cdc 1032// vim:set et sw=4 sts=4 sws=4 foldmethod=marker fenc=utf-8:
eb54852e 1033?>