Allows users to notify erroneous geocoding.
[platal.git] / classes / address.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2011 Polytechnique.org *
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 *
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 *
50 * Thus an Address can be linked to a Company, a Profile, or a Job.
51 */
52 class Address
53 {
54 const LINK_JOB = 'job';
55 const LINK_COMPANY = 'hq';
56 const LINK_PROFILE = 'home';
57 const LINK_GROUP = 'group';
58
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
291 // Primary key fields: the quadruplet ($pid, $jobid, $type, $id) defines a unique address.
292 public $pid = 0;
293 public $jobid = 0;
294 public $groupid = 0;
295 public $type = Address::LINK_PROFILE;
296 public $id = 0;
297
298 // Geocoding fields.
299 public $text = '';
300 public $postalText = '';
301 public $types = '';
302 public $formatted_address = '';
303 public $components = array();
304 public $latitude = null;
305 public $longitude = null;
306 public $southwest_latitude = null;
307 public $southwest_longitude = null;
308 public $northeast_latitude = null;
309 public $northeast_longitude = null;
310 public $location_type = '';
311 public $partial_match = false;
312 public $componentsIds = '';
313 public $request = false;
314
315 // Database's field required for both 'home' and 'job' addresses.
316 public $pub = 'ax';
317
318 // Database's fields required for 'home' addresses.
319 public $flags = null; // 'current', 'temporary', 'secondary', 'mail', 'cedex', 'deliveryIssue'
320 public $comment = null;
321 public $current = null;
322 public $temporary = null;
323 public $secondary = null;
324 public $mail = null;
325 public $deliveryIssue = null;
326
327 // Remaining fields that do not belong to profile_addresses.
328 public $phones = array();
329 public $error = false;
330 public $changed = 0;
331 public $removed = 0;
332
333 public function __construct(array $data = array())
334 {
335 if (count($data) > 0) {
336 foreach ($data as $key => $val) {
337 $this->$key = $val;
338 }
339 }
340
341 if (!is_null($this->flags)) {
342 $this->flags = new PlFlagSet($this->flags);
343 } else {
344 static $flags = array('current', 'temporary', 'secondary', 'mail', 'deliveryIssue');
345
346 $this->flags = new PlFlagSet();
347 foreach ($flags as $flag) {
348 if (!is_null($this->$flag) && ($this->$flag == 1 || $this->$flag == 'on')) {
349 $this->flags->addFlag($flag, 1);
350 $this->$flag = null;
351 }
352 $this->flags->addFlag('cedex', (strpos(strtoupper(preg_replace(array("/[0-9,\"'#~:;_\- ]/", "/\r\n/"),
353 array('', "\n"), $this->text)), 'CEDEX')) !== false);
354 }
355 }
356 $this->request = !is_null(AddressReq::get_request($this->pid, $this->jobid, $this->groupid, $this->type, $this->text));
357 }
358
359 public function setId($id)
360 {
361 $this->id = $id;
362 }
363
364 public function phones()
365 {
366 return $this->phones;
367 }
368
369 public function addPhone(Phone $phone)
370 {
371 if ($phone->link_type == Phone::LINK_ADDRESS && $phone->pid == $this->pid) {
372 $this->phones[$phone->uniqueId()] = $phone;
373 }
374 }
375
376 public function hasFlag($flag)
377 {
378 return ($this->flags != null && $this->flags->hasFlag($flag));
379 }
380
381 public function addFlag($flag)
382 {
383 $this->flags->addFlag($flag);
384 }
385
386 /** Auxilary function for formatting postal addresses.
387 * If the needle is found in the haystack, it notifies the substitution's
388 * success, modifies the length accordingly and returns either the matching
389 * substitution or the needle.
390 */
391 private function substitute($needle, $haystack, &$length, &$success, $trim = false)
392 {
393 if (array_key_exists($needle, $haystack)) {
394 $success = true;
395 $length -= (strlen($needle) - strlen($haystack[$needle]));
396 return $haystack[$needle];
397 } elseif ($trim) {
398 $success = true;
399 if (strlen($needle) > 4) {
400 $length -= (strlen($needle) - 4);
401 $needle = $needle{4};
402 }
403 }
404 return $needle;
405 }
406
407 /** Checks if the line corresponds to a French street line.
408 * A line is considered a French street line if it starts by between 1 and 4 numbers.
409 */
410 private function isStreetFR($line)
411 {
412 return preg_match('/^\d{1,4}\D/', $line);
413 }
414
415 /** Retrieves a French street number and slit the rest of the line into an array.
416 * @param $words: array containing the rest of the line (a word per cell).
417 * @param $line: line to consider.
418 * Returns the street number.
419 */
420 private function getStreetNumberFR(&$line)
421 {
422 // First we define numbers and separators.
423 $numberReq = '(\d{1,4})\s*(BIS|TER|QUATER|[A-Z])?';
424 $separatorReq = '\s*(?:\\|-|&|A|ET)?\s*';
425
426 // Then we retrieve the number(s) and the rest of the line.
427 // $matches contains:
428 // -0: the full patern, here the given line,
429 // -1: the number,
430 // -2: its optionnal quantifier,
431 // -3: an optionnal second number,
432 // -4: the second number's optionnal quantifier,
433 // -5: the rest of the line.
434 preg_match('/^' . $numberReq . '(?:' . $separatorReq . $numberReq . ')?\s+(.*)/', $line, $matches);
435 $number = $matches[1];
436 $line = $matches[5];
437
438 // If there is a precision on the address, we concatenate it to the number.
439 if ($matches[2] != '') {
440 $number .= $matches[2]{0};
441 } elseif ($matches[4] != '') {
442 $number .= $matches[4]{0};
443 }
444
445 return $number;
446 }
447
448 /** Checks if the line corresponds to a French locality line.
449 * A line is considered a French locality line if it starts by exactly a
450 * postal code of exactly 5 numbers.
451 */
452 private function isLocalityFR($line)
453 {
454 return preg_match('/^\d{5}\D/', $line);
455 }
456
457 /** Retrieves a French postal code and slit the rest of the line into an array.
458 * @param $words: array containing the rest of the line (a word per cell).
459 * @param $line: line to consider.
460 * Returns the postal code, and cuts it out from the line.
461 */
462 private function getPostalCodeFR(&$line)
463 {
464 $number = substr($line, 0, 5);
465 $line = trim(substr($line, 5));
466 return $number;
467 }
468
469 /** Returns the address formated for French postal use (cf AFNOR XPZ 10-011).
470 * A postal addresse containts at most 6 lines of at most 38 characters each:
471 * - addressee's identification ("MONSIEUR JEAN DURAND", "DURAND SA"…),
472 * - delivery point identification ("CHEZ TOTO APPARTEMENT 2", "SERVICE ACHAT"…),
473 * - building localisation complement ("ENTREE A BATIMENT DES JONQUILLES", "ZONE INDUSTRIELLE OUEST"…),
474 * - N° and street name ("25 RUE DES FLEURS", "LES VIGNES"…),
475 * - delivery service, street localisation complement ("BP 40122", "BP 40112 AREYRES"…),
476 * - postal code and locality or cedex code and cedex ("33500 LIBOURNE", "33506 LIBOURNE CEDEX"…).
477 * Punctuation must be removed, all leters must be uppercased.
478 * Both locality and street name must not take more than 32 characters.
479 *
480 * @param $arrayText: array containing the address to be formated, one
481 * address line per array line.
482 * @param $count: array size.
483 */
484 private function formatPostalAddressFR($arrayText)
485 {
486 // First removes country if any.
487 $count = count($arrayText);
488 if ($arrayText[$count - 1] == 'FRANCE') {
489 unset($arrayText[$count - 1]);
490 --$count;
491 }
492
493 // All the lines must have less than 38 characters but street and
494 // locality lines whose limit is 32 characters.
495 foreach ($arrayText as $lineNumber => $line) {
496 if ($isStreetLine = $this->isStreetFR($line)) {
497 $formattedLine = $this->getStreetNumberFR($line) . ' ';
498 $limit = 32;
499 } elseif ($this->isLocalityFR($line)) {
500 $formattedLine = $this->getPostalCodeFR($line) . ' ';
501 $limit = 32;
502 } else {
503 $formattedLine = '';
504 $limit = 38;
505 }
506
507 $words = explode(' ', $line);
508 $count = count($words);
509 $length = $count - 1;
510 foreach ($words as $word) {
511 $length += strlen($word);
512 }
513
514 // Checks is length is ok. Otherwise, we try to shorten words and
515 // update the length of the current line accordingly.
516 for ($i = 0; $i < $count && $length > $limit; ++$i) {
517 $success = false;
518 if ($isStreetLine) {
519 $sub = $this->substitute($words[$i], Address::$streetAbbreviations, $length, $success, ($i == 0));
520 }
521 // Entreprises' substitution are only suitable for the first two lines.
522 if ($lineNumber <= 2 && !$success) {
523 $sub = $this->substitute($words[$i], Address::$entrepriseAbbreviations, $length, $success);
524 }
525 if (!$success) {
526 $sub = $this->substitute($words[$i], Address::$otherAbbreviations, $length, $success);
527 }
528
529 $formattedLine .= $sub . ' ';
530 }
531 for (; $i < $count; ++$i) {
532 $formattedLine .= $words[$i] . ' ';
533 }
534 $arrayText[$lineNumber] = trim($formattedLine);
535 }
536
537 return implode("\n", $arrayText);
538 }
539
540 // Formats postal addresses.
541 // First erases punctuation, accents… Then uppercase the address and finally
542 // calls the country's dedicated formatting function.
543 public function formatPostalAddress()
544 {
545 // Performs rough formatting.
546 $text = mb_strtoupper(replace_accent($this->text));
547 $text = str_replace(array(',', ';', '.', ':', '!', '?', '"', '«', '»'), '', $text);
548 $text = preg_replace('/( |\t)+/', ' ', $text);
549 $arrayText = explode("\n", $text);
550 $arrayText = array_map('trim', $arrayText);
551
552 // Formats according to country rules. Thus we first identify the
553 // country, then apply corresponding formatting or translate country
554 // into default language.
555 $count = count($arrayText);
556 list($countryId, $country) = XDB::fetchOneRow('SELECT gc.iso_3166_1_a2, gc.country
557 FROM geoloc_countries AS gc
558 INNER JOIN geoloc_languages AS gl ON (gc.iso_3166_1_a2 = gl.iso_3166_1_a2)
559 WHERE gl.countryPlain = {?} OR gc.countryPlain = {?}',
560 $arrayText[$count - 1], $arrayText[$count - 1]);
561 if (is_null($countryId)) {
562 $text = $this->formatPostalAddressFR($arrayText);
563 } elseif (in_array(strtoupper($countryId), Address::$formattings)) {
564 $text = call_user_func(array($this, 'formatPostalAddress' . strtoupper($countryId)), $arrayText);
565 } else {
566 $arrayText[$count - 1] = mb_strtoupper(replace_accent($country));
567 $text = implode("\n", $arrayText);
568 }
569
570 $this->postalText = $text;
571 }
572
573 public function format()
574 {
575 $this->text = trim($this->text);
576 $this->phones = Phone::formatFormArray($this->phones, $this->error, new ProfileVisibility($this->pub));
577 if ($this->removed == 1) {
578 if (!S::user()->checkPerms('directory_private') && Phone::hasPrivate($this->phones)) {
579 Platal::page()->trigWarning("L'adresse ne peut être supprimée car elle contient des informations pour lesquelles vous n'avez le droit d'édition.");
580 } else {
581 $this->text = '';
582 return true;
583 }
584 }
585
586 $this->formatPostalAddress();
587 if ($this->changed == 1) {
588 $gmapsGeocoder = new GMapsGeocoder();
589 $gmapsGeocoder->getGeocodedAddress($this);
590 }
591
592 $componants = array();
593 foreach ($this->components as $component) {
594 $componants[] = Geocoder::getComponentId($component);
595 }
596 $this->componentsIds = implode(',', $componants);
597
598 return true;
599 }
600
601 public function toFormArray()
602 {
603 $address = array(
604 'text' => $this->text,
605 'postalText' => $this->postalText,
606 'types' => $this->types,
607 'formatted_address' => $this->formatted_address,
608 'latitude' => $this->latitude,
609 'longitude' => $this->longitude,
610 'southwest_latitude' => $this->southwest_latitude,
611 'southwest_longitude' => $this->southwest_longitude,
612 'northeast_latitude' => $this->northeast_latitude,
613 'northeast_longitude' => $this->northeast_longitude,
614 'location_type' => $this->location_type,
615 'partial_match' => $this->partial_match,
616 'componentsIds' => $this->componentsIds,
617 'request' => $this->request
618 );
619
620 if ($this->type == self::LINK_PROFILE || $this->type == self::LINK_JOB) {
621 $address['pub'] = $this->pub;
622 }
623 if ($this->type == self::LINK_PROFILE) {
624 static $flags = array('current', 'temporary', 'secondary', 'mail', 'cedex', 'deliveryIssue');
625 foreach ($flags as $flag) {
626 $address[$flag] = $this->flags->hasFlag($flag);
627 }
628 $address['comment'] = $this->comment;
629 $address['phones'] = Phone::formatFormArray($this->phones);
630 }
631
632 return $address;
633 }
634
635 private function toString()
636 {
637 $address = $this->text;
638 if ($this->type == self::LINK_PROFILE || $this->type == self::LINK_JOB) {
639 static $pubs = array('public' => 'publique', 'ax' => 'annuaire AX', 'private' => 'privé');
640 $address .= ' (affichage ' . $pubs[$this->pub];
641 }
642 if ($this->type == self::LINK_PROFILE) {
643 static $flags = array(
644 'current' => 'actuelle',
645 'temporary' => 'temporaire',
646 'secondary' => 'secondaire',
647 'mail' => 'conctactable par courier',
648 'deliveryIssue' => 'n\'habite pas à l\'adresse indiquée',
649 'cedex' => 'type cédex',
650 );
651
652 if (!$this->flags->hasFlag('temporary')) {
653 $address .= ', permanente';
654 }
655 if (!$this->flags->hasFlag('secondary')) {
656 $address .= ', principale';
657 }
658 foreach ($flags as $flag => $flagName) {
659 if ($this->flags->hasFlag($flag)) {
660 $address .= ', ' . $flagName;
661 }
662 }
663 if ($this->comment) {
664 $address .= ', commentaire : ' . $this->comment;
665 }
666 if ($phones = Phone::formArrayToString($this->phones)) {
667 $address .= ', ' . $phones;
668 }
669 } elseif ($this->type == self::LINK_JOB) {
670 $address .= ')';
671 }
672 return $address;
673 }
674
675 private function isEmpty()
676 {
677 return (!$this->text || $this->text == '');
678 }
679
680 public function save()
681 {
682 if (!$this->isEmpty()) {
683 XDB::execute('INSERT IGNORE INTO profile_addresses (pid, jobid, groupid, type, id, flags, text, postalText, pub, comment,
684 types, formatted_address, location_type, partial_match, latitude, longitude,
685 southwest_latitude, southwest_longitude, northeast_latitude, northeast_longitude)
686 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?},
687 {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?})',
688 $this->pid, $this->jobid, $this->groupid, $this->type, $this->id, $this->flags, $this->text, $this->postalText, $this->pub, $this->comment,
689 $this->types, $this->formatted_address, $this->location_type, $this->partial_match, $this->latitude, $this->longitude,
690 $this->southwest_latitude, $this->southwest_longitude, $this->northeast_latitude, $this->northeast_longitude);
691
692 if ($this->componentsIds) {
693 foreach (explode(',', $this->componentsIds) as $component_id) {
694 XDB::execute('INSERT IGNORE INTO profile_addresses_components (pid, jobid, groupid, type, id, component_id)
695 VALUES ({?}, {?}, {?}, {?}, {?}, {?})',
696 $this->pid, $this->jobid, $this->groupid, $this->type, $this->id, $component_id);
697 }
698 }
699
700 if ($this->type == self::LINK_PROFILE) {
701 Phone::savePhones($this->phones, $this->pid, Phone::LINK_ADDRESS, $this->id);
702 }
703 }
704 }
705
706 public function updateGeocoding($text)
707 {
708 $id = null;
709 $texts = XDB::fetchAllAssoc('id', 'SELECT id, text
710 FROM profile_addresses
711 WHERE pid = {?} AND jobid = {?} AND groupid = {?} AND type = {?}',
712 $this->pid, $this->jobid, $this->groupid, $this->type);
713 $text = preg_replace('/\s+/', ' ', $text);
714 foreach ($texts as $key => $value) {
715 if (strcmp($text, preg_replace('/\s+/', ' ', $value)) == 0) {
716 $id = $key;
717 break;
718 }
719 }
720 if (!is_null($id)) {
721 XDB::execute('UPDATE profile_addresses
722 SET text = {?}, postalText = {?}, types = {?}, formatted_address = {?},
723 location_type = {?}, partial_match = {?}, latitude = {?}, longitude = {?},
724 southwest_latitude = {?}, southwest_longitude = {?}, northeast_latitude = {?}, northeast_longitude = {?}
725 WHERE pid = {?} AND jobid = {?} AND groupid = {?} AND type = {?} AND id = {?}',
726 $this->text, $this->postalText, $this->types, $this->formatted_address,
727 $this->location_type, $this->partial_match, $this->latitude, $this->longitude,
728 $this->southwest_latitude, $this->southwest_longitude, $this->northeast_latitude, $this->northeast_longitude,
729 $this->pid, $this->jobid, $this->groupid, $this->type, $id);
730
731 XDB::execute('DELETE FROM profile_addresses_components
732 WHERE pid = {?} AND jobid = {?} AND groupid = {?} AND type = {?} AND id = {?}',
733 $this->pid, $this->jobid, $this->groupid, $this->type, $id);
734 if ($this->componentsIds) {
735 foreach (explode(',', $this->componentsIds) as $component_id) {
736 XDB::execute('INSERT IGNORE INTO profile_addresses_components (pid, jobid, groupid, type, id, component_id)
737 VALUES ({?}, {?}, {?}, {?}, {?}, {?})',
738 $this->pid, $this->jobid, $this->groupid, $this->type, $id, $component_id);
739 }
740 }
741 }
742 }
743
744 public function delete()
745 {
746 XDB::execute('DELETE FROM profile_addresses
747 WHERE pid = {?} AND jobid = {?} AND groupid = {?} AND type = {?} AND id = {?}',
748 $this->pid, $this->jobid, $this->groupid, $this->type, $this->id);
749 }
750
751 static public function deleteAddresses($pid, $type, $jobid = null, $groupid = null, $deletePrivate = true)
752 {
753 $where = '';
754 if (!is_null($pid)) {
755 $where = XDB::format(' AND pid = {?}', $pid);
756 }
757 if (!is_null($jobid)) {
758 $where = XDB::format(' AND jobid = {?}', $jobid);
759 }
760 if (!is_null($groupid)) {
761 $where = XDB::format(' AND groupid = {?}', $groupid);
762 }
763 XDB::execute('DELETE FROM profile_addresses
764 WHERE type = {?}' . $where . (($deletePrivate) ? '' : ' AND pub IN (\'public\', \'ax\')'),
765 $type);
766 if ($type == self::LINK_PROFILE) {
767 Phone::deletePhones($pid, Phone::LINK_ADDRESS, null, $deletePrivate);
768 }
769 }
770
771 /** Saves addresses into the database.
772 * @param $data: an array of form formatted addresses.
773 * @param $pid, $type, $linkid: pid, type and id concerned by the update.
774 */
775 static public function saveFromArray(array $data, $pid, $type = self::LINK_PROFILE, $linkid = null, $savePrivate = true)
776 {
777 foreach ($data as $id => $value) {
778 if ($value['pub'] != 'private' || $savePrivate) {
779 if (!is_null($linkid)) {
780 $value['id'] = $linkid;
781 } else {
782 $value['id'] = $id;
783 }
784 if (!is_null($pid)) {
785 $value['pid'] = $pid;
786 }
787 if (!is_null($type)) {
788 $value['type'] = $type;
789 }
790 $address = new Address($value);
791 $address->save();
792 }
793 }
794 }
795
796 static private function formArrayWalk(array $data, $function, &$success = true, $requiresEmptyAddress = false)
797 {
798 $addresses = array();
799 foreach ($data as $item) {
800 $address = new Address($item);
801 $success = ($address->format() && $success);
802 if (!$address->isEmpty()) {
803 $addresses[] = call_user_func(array($address, $function));
804 }
805 }
806 if (count($address) == 0 && $requiresEmptyAddress) {
807 $address = new Address();
808 $addresses[] = call_user_func(array($address, $function));
809 }
810 return $addresses;
811 }
812
813 // Compares two addresses. First sort by publicity, then place primary
814 // addresses before secondary addresses.
815 static private function compare(array $a, array $b)
816 {
817 $value = ProfileVisibility::comparePublicity($a, $b);
818 if ($value == 0) {
819 if ($a['secondary'] != $b['secondary']) {
820 $value = $a['secondary'] ? 1 : -1;
821 }
822 }
823 return $value;
824 }
825
826 // Formats an array of form addresses into an array of form formatted addresses.
827 static public function formatFormArray(array $data, &$success = true)
828 {
829 $addresses = self::formArrayWalk($data, 'toFormArray', $success, true);
830
831 // Only a single address can be the profile's current address and she must have one.
832 $hasCurrent = false;
833 foreach ($addresses as $key => &$address) {
834 if (isset($address['current']) && $address['current']) {
835 if ($hasCurrent) {
836 $address['current'] = false;
837 } else {
838 $hasCurrent = true;
839 }
840 }
841 }
842 if (!$hasCurrent && count($value) > 0) {
843 foreach ($value as &$address) {
844 $address['current'] = true;
845 break;
846 }
847 }
848
849 usort($addresses, 'Address::compare');
850 return $addresses;
851 }
852
853 static public function formArrayToString(array $data)
854 {
855 return implode(', ', self::formArrayWalk($data, 'toString'));
856 }
857
858 static public function hasPrivate(array $addresses)
859 {
860 foreach ($addresses as $address) {
861 if ($address['pub'] == 'private') {
862 return true;
863 }
864 }
865 return false;
866 }
867
868 static public function iterate(array $pids = array(), array $types = array(),
869 array $jobids = array(), array $pubs = array())
870 {
871 return new AddressIterator($pids, $types, $jobids, $pubs);
872 }
873 }
874
875 /** Iterator over a set of Phones
876 *
877 * @param $pid, $type, $jobid, $pub
878 *
879 * The iterator contains the phones that correspond to the value stored in the
880 * parameters' arrays.
881 */
882 class AddressIterator implements PlIterator
883 {
884 private $dbiter;
885
886 public function __construct(array $pids, array $types, array $jobids, array $pubs)
887 {
888 $where = array();
889 if (count($pids) != 0) {
890 $where[] = XDB::format('(pa.pid IN {?})', $pids);
891 }
892 if (count($types) != 0) {
893 $where[] = XDB::format('(pa.type IN {?})', $types);
894 }
895 if (count($jobids) != 0) {
896 $where[] = XDB::format('(pa.jobid IN {?})', $jobids);
897 }
898 if (count($pubs) != 0) {
899 $where[] = XDB::format('(pa.pub IN {?})', $pubs);
900 }
901 $sql = 'SELECT pa.pid, pa.jobid, pa.groupid, pa.type, pa.id, pa.flags, pa.text, pa.postalText, pa.pub, pa.comment,
902 pa.types, pa.formatted_address, pa.location_type, pa.partial_match, pa.latitude, pa.longitude,
903 pa.southwest_latitude, pa.southwest_longitude, pa.northeast_latitude, pa.northeast_longitude,
904 GROUP_CONCAT(DISTINCT pc.component_id SEPARATOR \',\') AS componentsIds
905 FROM profile_addresses AS pa
906 LEFT JOIN profile_addresses_components AS pc ON (pa.pid = pc.pid AND pa.jobid = pc.jobid AND pa.groupid = pc.groupid
907 AND pa.type = pc.type AND pa.id = pc.id)
908 ' . ((count($where) > 0) ? 'WHERE ' . implode(' AND ', $where) : '') . '
909 GROUP BY pa.pid, pa.jobid, pa.groupid, pa.type, pa.id
910 ORDER BY pa.pid, pa.jobid, pa.id';
911 $this->dbiter = XDB::iterator($sql);
912 }
913
914 public function next()
915 {
916 if (is_null($this->dbiter)) {
917 return null;
918 }
919 $data = $this->dbiter->next();
920 if (is_null($data)) {
921 return null;
922 }
923 // Adds phones to addresses.
924 $it = Phone::iterate(array($data['pid']), array(Phone::LINK_ADDRESS), array($data['id']));
925 while ($phone = $it->next()) {
926 $data['phones'][$phone->id] = $phone->toFormArray();
927 }
928 return new Address($data);
929 }
930
931 public function total()
932 {
933 return $this->dbiter->total();
934 }
935
936 public function first()
937 {
938 return $this->dbiter->first();
939 }
940
941 public function last()
942 {
943 return $this->dbiter->last();
944 }
945
946 public function value()
947 {
948 return $this->dbiter;
949 }
950 }
951
952 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
953 ?>