2 /***************************************************************************
3 * Copyright (C) 2003-2011 Polytechnique.org *
4 * http://opensource.polytechnique.org/ *
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. *
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. *
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 *
19 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
20 ***************************************************************************/
22 /** Class Address is meant to perform most of the access to the table profile_addresses.
24 * profile_addresses describes an Address, which can be related to either a
25 * Profile, a Job or a Company:
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
33 * - `type` is set to 'hq'
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)
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
45 * - `type` is set to 'group'
47 * - `jobid` is set to 0
48 * - `groupid` is set to the group id
50 * Thus an Address can be linked to a Company, a Profile, or a Job.
54 const LINK_JOB
= 'job';
55 const LINK_COMPANY
= 'hq';
56 const LINK_PROFILE
= 'home';
57 const LINK_GROUP
= 'group';
59 // List of all available postal formattings.
60 private static $formattings = array('FRANCE' => 'FR');
62 // Abbreviations to be used to format French postal addresses.
63 private static $streetAbbreviations = array(
68 'CENTRE COMMERCIAL' => 'CCAL',
73 'LOTISSEMENT' => 'LOT',
77 'ROND-POINT' => 'RPT',
81 'ZONE D\'ACTIVITE' => 'ZA',
82 'ZONE D\'AMENAGEMENT CONCERTE' => 'ZAC',
83 'ZONE D\'AMENAGEMENT DIFFERE' => 'ZAD',
84 'ZONE INDUSTRIELLE' => 'ZI'
86 private static $otherAbbreviations = array(
88 'AERODROME' => 'AERD',
90 'AERONAUTIQUE' => 'AERN',
93 'AGRICOLE' => 'AGRIC',
95 'ANCIENNEMENT' => 'ANC',
96 'APPARTEMENT' => 'APP',
97 'APPARTEMENTS' => 'APP',
99 'ARRONDISSEMENT' => 'ARR',
101 'ASSOCIATION' => 'ASSOC',
102 'ASSURANCE' => 'ASSUR',
104 'BARAQUEMENT' => 'BRQ',
108 'BATAILLON' => 'BTN',
109 'BATAILLONS' => 'BTN',
111 'BATIMENTS' => 'BAT',
113 'BOITE POSTALE' => 'BP',
117 'CASE POSTALE' => 'CP',
119 'CITADELLE' => 'CTD',
124 'COMMANDANT' => 'CDT',
125 'COMMERCIAL' => 'CIAL',
128 'COMMUNAUX' => 'COM',
129 'COMPAGNIE' => 'CIE',
130 'COMPAGNON' => 'COMP',
131 'COMPAGNONS' => 'COMP',
132 'COOPERATIVE' => 'COOP',
133 'COURSE SPECIALE' => 'CS',
135 'DELEGATION' => 'DELEG',
136 'DEPARTEMENTAL' => 'DEP',
137 'DEPARTEMENTAUX' => 'DEP',
138 'DIRECTEUR' => 'DIR',
139 'DIRECTECTION' => 'DIR',
143 'ECONOMIQUE' => 'ECO',
144 'ECRIVAIN' => 'ECRIV',
145 'ECRIVAINS' => 'ECRIV',
146 'ENSEIGNEMENT' => 'ENST',
150 'ENTREPRISE' => 'ENTR',
153 'ETABLISSEMENT' => 'ETS',
155 'ETAT MAJOR' => 'EM',
159 'FORESTIER' => 'FOR',
163 'GENDARMERIE' => 'GEND',
165 'GOUVERNEMENTAL' => 'GOUV',
166 'GOUVERNEUR' => 'GOU',
178 'HOSPITALIER' => 'HOSP',
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',
192 'MADEMOISELLE' => 'MLLE',
200 'MESDAMES' => 'MMES',
201 'MESDEMOISELLES' => 'MLLES',
203 'MILITAIRE' => 'MIL',
204 'MINISTERE' => 'MIN',
205 'MONSEIGNEUR' => 'MGR',
207 'MUNICIPAL' => 'MUN',
210 'NOTRE DAME' => 'ND',
213 'NOUVELLE' => 'NOUV',
214 'OBSERVATOIRE' => 'OBS',
222 'PREFECTURE' => 'PREF',
223 'PRESIDENT' => 'PDT',
224 'PROFESSEUR' => 'PR',
225 'PROFESSIONNEL' => 'PROF',
226 'PROFESSIONNELE' => 'PROF',
227 'PROLONGE' => 'PROL',
228 'PROLONGEE' => 'PROL',
229 'PROPRIETE' => 'PROP',
236 'REGIONALE' => 'REG',
237 'REPUBLIQUE' => 'REP',
238 'RESTAURANT' => 'REST',
243 'SANATORIUM' => 'SANA',
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',
256 'TRI SERVICE ARRIVEE' => 'TSA',
258 'UNIVERSITAIRE' => 'UNVT',
259 'UNIVERSITE' => 'UNIV',
260 'VELODROME' => 'VELOD',
263 'VIEILLES' => 'VIEL',
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'
291 // Primary key fields: the quadruplet ($pid, $jobid, $type, $id) defines a unique address.
295 public $type = Address
::LINK_PROFILE
;
299 public $accuracy = 0;
301 public $postalText = '';
302 public $postalCode = null
;
303 public $localityId = null
;
304 public $subAdministrativeAreaId = null
;
305 public $administrativeAreaId = null
;
306 public $localityName = null
;
307 public $subAdministrativeAreaName = null
;
308 public $administrativeAreaName = null
;
309 public $localityNameLocal = null
;
310 public $subAdministrativeAreaNameLocal = null
;
311 public $administrativeAreaNameLocal = null
;
312 public $countryId = null
;
313 public $latitude = null
;
314 public $longitude = null
;
315 public $north = null
;
316 public $south = null
;
319 public $geocodedText = null
;
320 public $geocodeChosen = null
;
322 // Database's field required for both 'home' and 'job' addresses.
325 // Database's fields required for 'home' addresses.
326 public $flags = null
; // 'current', 'temporary', 'secondary', 'mail', 'cedex', 'deliveryIssue'
327 public $comment = null
;
328 public $current = null
;
329 public $temporary = null
;
330 public $secondary = null
;
332 public $deliveryIssue = null
;
334 // Remaining fields that do not belong to profile_addresses.
335 public $phones = array();
336 public $error = false
;
340 public function __construct(array $data = array())
342 if (count($data) > 0) {
343 foreach ($data as $key => $val) {
348 if (!is_null($this->flags
)) {
349 $this->flags
= new PlFlagSet($this->flags
);
351 static $flags = array('current', 'temporary', 'secondary', 'mail', 'deliveryIssue');
353 $this->flags
= new PlFlagSet();
354 foreach ($flags as $flag) {
355 if (!is_null($this->$flag) && ($this->$flag == 1 ||
$this->$flag == 'on')) {
356 $this->flags
->addFlag($flag, 1);
359 $this->flags
->addFlag('cedex', (strpos(strtoupper(preg_replace(array("/[0-9,\"'#~:;_\- ]/", "/\r\n/"),
360 array('', "\n"), $this->text
)), 'CEDEX')) !== false
);
365 public function setId($id)
370 public function phones()
372 return $this->phones
;
375 public function addPhone(Phone
$phone)
377 if ($phone->link_type
== Phone
::LINK_ADDRESS
&& $phone->pid
== $this->pid
) {
378 $this->phones
[$phone->uniqueId()] = $phone;
382 public function hasFlag($flag)
384 return ($this->flags
!= null
&& $this->flags
->hasFlag($flag));
387 public function addFlag($flag)
389 $this->flags
->addFlag($flag);
392 /** Auxilary function for formatting postal addresses.
393 * If the needle is found in the haystack, it notifies the substitution's
394 * success, modifies the length accordingly and returns either the matching
395 * substitution or the needle.
397 private function substitute($needle, $haystack, &$length, &$success, $trim = false
)
399 if (array_key_exists($needle, $haystack)) {
401 $length -= (strlen($needle) - strlen($haystack[$needle]));
402 return $haystack[$needle];
405 if (strlen($needle) > 4) {
406 $length -= (strlen($needle) - 4);
407 $needle = $needle{4};
413 /** Checks if the line corresponds to a French street line.
414 * A line is considered a French street line if it starts by between 1 and 4 numbers.
416 private function isStreetFR($line)
418 return preg_match('/^\d{1,4}\D/', $line);
421 /** Retrieves a French street number and slit the rest of the line into an array.
422 * @param $words: array containing the rest of the line (a word per cell).
423 * @param $line: line to consider.
424 * Returns the street number.
426 private function getStreetNumberFR(&$line)
428 // First we define numbers and separators.
429 $numberReq = '(\d{1,4})\s*(BIS|TER|QUATER|[A-Z])?';
430 $separatorReq = '\s*(?:\\|-|&|A|ET)?\s*';
432 // Then we retrieve the number(s) and the rest of the line.
433 // $matches contains:
434 // -0: the full patern, here the given line,
436 // -2: its optionnal quantifier,
437 // -3: an optionnal second number,
438 // -4: the second number's optionnal quantifier,
439 // -5: the rest of the line.
440 preg_match('/^' . $numberReq . '(?:' . $separatorReq . $numberReq . ')?\s+(.*)/', $line, $matches);
441 $number = $matches[1];
444 // If there is a precision on the address, we concatenate it to the number.
445 if ($matches[2] != '') {
446 $number .= $matches[2]{0};
447 } elseif ($matches[4] != '') {
448 $number .= $matches[4]{0};
454 /** Checks if the line corresponds to a French locality line.
455 * A line is considered a French locality line if it starts by exactly a
456 * postal code of exactly 5 numbers.
458 private function isLocalityFR($line)
460 return preg_match('/^\d{5}\D/', $line);
463 /** Retrieves a French postal code and slit the rest of the line into an array.
464 * @param $words: array containing the rest of the line (a word per cell).
465 * @param $line: line to consider.
466 * Returns the postal code, and cuts it out from the line.
468 private function getPostalCodeFR(&$line)
470 $number = substr($line, 0, 5);
471 $line = trim(substr($line, 5));
475 /** Returns the address formated for French postal use (cf AFNOR XPZ 10-011).
476 * A postal addresse containts at most 6 lines of at most 38 characters each:
477 * - addressee's identification ("MONSIEUR JEAN DURAND", "DURAND SA"…),
478 * - delivery point identification ("CHEZ TOTO APPARTEMENT 2", "SERVICE ACHAT"…),
479 * - building localisation complement ("ENTREE A BATIMENT DES JONQUILLES", "ZONE INDUSTRIELLE OUEST"…),
480 * - N° and street name ("25 RUE DES FLEURS", "LES VIGNES"…),
481 * - delivery service, street localisation complement ("BP 40122", "BP 40112 AREYRES"…),
482 * - postal code and locality or cedex code and cedex ("33500 LIBOURNE", "33506 LIBOURNE CEDEX"…).
483 * Punctuation must be removed, all leters must be uppercased.
484 * Both locality and street name must not take more than 32 characters.
486 * @param $arrayText: array containing the address to be formated, one
487 * address line per array line.
488 * @param $count: array size.
490 private function formatPostalAddressFR($arrayText)
492 // First removes country if any.
493 $count = count($arrayText);
494 if ($arrayText[$count - 1] == 'FRANCE') {
495 unset($arrayText[$count - 1]);
499 // All the lines must have less than 38 characters but street and
500 // locality lines whose limit is 32 characters.
501 foreach ($arrayText as $lineNumber => $line) {
502 if ($isStreetLine = $this->isStreetFR($line)) {
503 $formattedLine = $this->getStreetNumberFR($line) . ' ';
505 } elseif ($this->isLocalityFR($line)) {
506 $formattedLine = $this->getPostalCodeFR($line) . ' ';
513 $words = explode(' ', $line);
514 $count = count($words);
515 $length = $count - 1;
516 foreach ($words as $word) {
517 $length +
= strlen($word);
520 // Checks is length is ok. Otherwise, we try to shorten words and
521 // update the length of the current line accordingly.
522 for ($i = 0; $i < $count && $length > $limit; ++
$i) {
525 $sub = $this->substitute($words[$i], Address
::$streetAbbreviations, $length, $success, ($i == 0));
527 // Entreprises' substitution are only suitable for the first two lines.
528 if ($lineNumber <= 2 && !$success) {
529 $sub = $this->substitute($words[$i], Address
::$entrepriseAbbreviations, $length, $success);
532 $sub = $this->substitute($words[$i], Address
::$otherAbbreviations, $length, $success);
535 $formattedLine .= $sub . ' ';
537 for (; $i < $count; ++
$i) {
538 $formattedLine .= $words[$i] . ' ';
540 $arrayText[$lineNumber] = trim($formattedLine);
543 return implode("\n", $arrayText);
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()
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);
558 // Formats according to country rules. Thus we first identify the
559 // country, then apply corresponding formatting or translate country
560 // into default language.
561 $count = count($arrayText);
562 if (in_array(strtoupper($this->countryId
), Address
::$formattings)) {
563 $text = call_user_func(array($this, 'formatPostalAddress' . strtoupper($this->countryId
)), $arrayText);
565 list($countryId, $country) = XDB
::fetchOneRow('SELECT gc.iso_3166_1_a2, gc.country
566 FROM geoloc_countries AS gc
567 INNER JOIN geoloc_languages AS gl ON (gc.iso_3166_1_a2 = gl.iso_3166_1_a2)
568 WHERE gc.iso_3166_1_a2 = {?} OR gl.countryPlain = {?} OR gc.countryPlain = {?}',
569 $this->countryId
, $arrayText[$count - 1], $arrayText[$count - 1]);
570 if (is_null($countryId)) {
571 $text = $this->formatPostalAddressFR($arrayText);
572 } elseif (in_array(strtoupper($countryId), Address
::$formattings)) {
573 $text = call_user_func(array($this, 'formatPostalAddress' . strtoupper($countryId)), $arrayText);
575 $arrayText[$count - 1] = mb_strtoupper(replace_accent($country));
576 $text = implode("\n", $arrayText);
580 $this->postalText
= $text;
583 public function format(array $format = array())
585 if (empty($format)) {
586 $format['requireGeocoding'] = false
;
587 $format['stripGeocoding'] = false
;
588 $format['postalText'] = false
;
590 foreach (array('requireGeocoding', 'stripGeocoding', 'postalText') as $type) {
591 $format[$type] = (isset($format[$type])) ?
$format[$type] : false
;
594 $this->text
= trim($this->text
);
595 $this->phones
= Phone
::formatFormArray($this->phones
, $this->error
, new ProfileVisibility($this->pub
));
596 if ($this->removed
== 1) {
597 if (!S
::user()->checkPerms('directory_private') && Phone
::hasPrivate($this->phones
)) {
598 Platal
::page()->trigWarning("L'adresse ne peut être supprimée car elle contient des informations pour lesquelles vous n'avez le droit d'édition.");
605 if ($format['requireGeocoding'] ||
$this->changed
== 1) {
606 $gmapsGeocoder = new GMapsGeocoder();
607 $gmapsGeocoder->getGeocodedAddress($this);
609 $this->error
= !empty($this->geocodedText
);
611 if ($format['stripGeocoding'] ||
($this->type
== self
::LINK_COMPANY
&& $this->error
) ||
$this->geocodeChosen
=== '0') {
612 if ($this->geocodeChosen
=== '0') {
613 $mailer = new PlMailer('profile/geocoding.mail.tpl');
614 $mailer->assign('text', $this->text
);
615 $mailer->assign('geoloc', $this->geocodedText
);
618 $gmapsGeocoder = new GMapsGeocoder();
619 $gmapsGeocoder->stripGeocodingFromAddress($this);
621 if ($this->countryId
== '') {
622 $this->countryId
= null
;
624 $this->geocodeChosen
= null
;
625 if ($format['postalText']) {
626 $this->formatPostalAddress();
628 return !$this->error
;
631 public function toFormArray()
634 'accuracy' => $this->accuracy
,
635 'text' => $this->text
,
636 'postalText' => $this->postalText
,
637 'postalCode' => $this->postalCode
,
638 'localityId' => $this->localityId
,
639 'subAdministrativeAreaId' => $this->subAdministrativeAreaId
,
640 'administrativeAreaId' => $this->administrativeAreaId
,
641 'countryId' => $this->countryId
,
642 'localityName' => $this->localityName
,
643 'subAdministrativeAreaName' => $this->subAdministrativeAreaName
,
644 'administrativeAreaName' => $this->administrativeAreaName
,
645 'localityNameLocal' => $this->localityNameLocal
,
646 'subAdministrativeAreaNameLocal' => $this->subAdministrativeAreaNameLocal
,
647 'administrativeAreaNameLocal' => $this->administrativeAreaNameLocal
,
648 'latitude' => $this->latitude
,
649 'longitude' => $this->longitude
,
650 'north' => $this->north
,
651 'south' => $this->south
,
652 'east' => $this->east
,
653 'west' => $this->west
,
654 'error' => $this->error
,
655 'changed' => $this->changed
,
656 'removed' => $this->removed
,
658 if (!is_null($this->geocodedText
)) {
659 $address['geocodedText'] = $this->geocodedText
;
660 $address['geocodeChosen'] = $this->geocodeChosen
;
663 if ($this->type
== self
::LINK_PROFILE ||
$this->type
== self
::LINK_JOB
) {
664 $address['pub'] = $this->pub
;
666 if ($this->type
== self
::LINK_PROFILE
) {
667 static $flags = array('current', 'temporary', 'secondary', 'mail', 'cedex', 'deliveryIssue');
669 foreach ($flags as $flag) {
670 $address[$flag] = $this->flags
->hasFlag($flag);
672 $address['comment'] = $this->comment
;
673 $address['phones'] = Phone
::formatFormArray($this->phones
);
679 private function toString()
681 $address = $this->text
;
682 if ($this->type
== self
::LINK_PROFILE ||
$this->type
== self
::LINK_JOB
) {
683 static $pubs = array('public' => 'publique', 'ax' => 'annuaire AX', 'private' => 'privé');
684 $address .= ' (affichage ' . $pubs[$this->pub
];
686 if ($this->type
== self
::LINK_PROFILE
) {
687 static $flags = array(
688 'current' => 'actuelle',
689 'temporary' => 'temporaire',
690 'secondary' => 'secondaire',
691 'mail' => 'conctactable par courier',
692 'deliveryIssue' => 'n\'habite pas à l\'adresse indiquée',
693 'cedex' => 'type cédex',
696 if (!$this->flags
->hasFlag('temporary')) {
697 $address .= ', permanente';
699 if (!$this->flags
->hasFlag('secondary')) {
700 $address .= ', principale';
702 foreach ($flags as $flag => $flagName) {
703 if ($this->flags
->hasFlag($flag)) {
704 $address .= ', ' . $flagName;
707 if ($this->comment
) {
708 $address .= ', commentaire : ' . $this->comment
;
710 if ($phones = Phone
::formArrayToString($this->phones
)) {
711 $address .= ', ' . $phones;
713 } elseif ($this->type
== self
::LINK_JOB
) {
719 private function isEmpty()
721 return (!$this->text ||
$this->text
== '');
724 public function save()
726 static $areas = array('administrativeArea', 'subAdministrativeArea', 'locality');
728 $this->format(array('postalText' => true
));
729 if (!$this->isEmpty()) {
730 foreach ($areas as $area) {
731 Geocoder
::getAreaId($this, $area);
734 XDB
::execute('INSERT IGNORE INTO profile_addresses (pid, jobid, groupid, type, id, flags, accuracy,
735 text, postalText, postalCode, localityId,
736 subAdministrativeAreaId, administrativeAreaId,
737 countryId, latitude, longitude, pub, comment,
738 north, south, east, west)
739 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?},
740 {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?})',
741 $this->pid
, $this->jobid
, $this->groupid
, $this->type
, $this->id
, $this->flags
, $this->accuracy
,
742 $this->text
, $this->postalText
, $this->postalCode
, $this->localityId
,
743 $this->subAdministrativeAreaId
, $this->administrativeAreaId
,
744 $this->countryId
, $this->latitude
, $this->longitude
,
745 $this->pub
, $this->comment
,
746 $this->north
, $this->south
, $this->east
, $this->west
);
748 if ($this->type
== self
::LINK_PROFILE
) {
749 Phone
::savePhones($this->phones
, $this->pid
, Phone
::LINK_ADDRESS
, $this->id
);
754 public function delete()
756 XDB
::execute('DELETE FROM profile_addresses
757 WHERE pid = {?} AND jobid = {?} AND groupid = {?} AND type = {?} AND id = {?}',
758 $this->pid
, $this->jobid
, $this->groupid
, $this->type
, $this->id
);
761 static public function deleteAddresses($pid, $type, $jobid = null
, $groupid = null
, $deletePrivate = true
)
764 if (!is_null($pid)) {
765 $where = XDB
::format(' AND pid = {?}', $pid);
767 if (!is_null($jobid)) {
768 $where = XDB
::format(' AND jobid = {?}', $jobid);
770 if (!is_null($groupid)) {
771 $where = XDB
::format(' AND groupid = {?}', $groupid);
773 XDB
::execute('DELETE FROM profile_addresses
774 WHERE type = {?}' . $where . (($deletePrivate) ?
'' : ' AND pub IN (\'public\', \'ax\')'),
776 if ($type == self
::LINK_PROFILE
) {
777 Phone
::deletePhones($pid, Phone
::LINK_ADDRESS
, null
, $deletePrivate);
781 /** Saves addresses into the database.
782 * @param $data: an array of form formatted addresses.
783 * @param $pid, $type, $linkid: pid, type and id concerned by the update.
785 static public function saveFromArray(array $data, $pid, $type = self
::LINK_PROFILE
, $linkid = null
, $savePrivate = true
)
787 foreach ($data as $id => $value) {
788 if ($value['pub'] != 'private' ||
$savePrivate) {
789 if (!is_null($linkid)) {
790 $value['id'] = $linkid;
794 if (!is_null($pid)) {
795 $value['pid'] = $pid;
797 if (!is_null($type)) {
798 $value['type'] = $type;
800 $address = new Address($value);
806 static private function formArrayWalk(array $data, $function, &$success = true
, $requiresEmptyAddress = false
)
808 $addresses = array();
809 foreach ($data as $item) {
810 $address = new Address($item);
811 $success = ($address->format() && $success);
812 if (!$address->isEmpty()) {
813 $addresses[] = call_user_func(array($address, $function));
816 if (count($address) == 0 && $requiresEmptyAddress) {
817 $address = new Address();
818 $addresses[] = call_user_func(array($address, $function));
823 // Compares two addresses. First sort by publicity, then place primary
824 // addresses before secondary addresses.
825 static private function compare(array $a, array $b)
827 $value = ProfileVisibility
::comparePublicity($a, $b);
829 if ($a['secondary'] != $b['secondary']) {
830 $value = $a['secondary'] ?
1 : -1;
836 // Formats an array of form addresses into an array of form formatted addresses.
837 static public function formatFormArray(array $data, &$success = true
)
839 $addresses = self
::formArrayWalk($data, 'toFormArray', $success, true
);
841 // Only a single address can be the profile's current address and she must have one.
843 foreach ($addresses as $key => &$address) {
844 if (isset($address['current']) && $address['current']) {
846 $address['current'] = false
;
852 if (!$hasCurrent && count($value) > 0) {
853 foreach ($value as &$address) {
854 $address['current'] = true
;
859 usort($addresses, 'Address::compare');
863 static public function formArrayToString(array $data)
865 return implode(', ', self
::formArrayWalk($data, 'toString'));
868 static public function hasPrivate(array $addresses)
870 foreach ($addresses as $address) {
871 if ($address['pub'] == 'private') {
878 static public function iterate(array $pids = array(), array $types = array(),
879 array $jobids = array(), array $pubs = array())
881 return new AddressIterator($pids, $types, $jobids, $pubs);
885 /** Iterator over a set of Phones
887 * @param $pid, $type, $jobid, $pub
889 * The iterator contains the phones that correspond to the value stored in the
890 * parameters' arrays.
892 class AddressIterator
implements PlIterator
896 public function __construct(array $pids, array $types, array $jobids, array $pubs)
899 if (count($pids) != 0) {
900 $where[] = XDB
::format('(pa.pid IN {?})', $pids);
902 if (count($types) != 0) {
903 $where[] = XDB
::format('(pa.type IN {?})', $types);
905 if (count($jobids) != 0) {
906 $where[] = XDB
::format('(pa.jobid IN {?})', $jobids);
908 if (count($pubs) != 0) {
909 $where[] = XDB
::format('(pa.pub IN {?})', $pubs);
911 $sql = 'SELECT pa.pid, pa.jobid, pa.type, pa.id, pa.flags,
912 pa.accuracy, pa.text, pa.postalText, pa.postalCode,
913 pa.localityId, pa.subAdministrativeAreaId,
914 pa.administrativeAreaId, pa.countryId,
915 pa.latitude, pa.longitude, pa.north, pa.south, pa.east, pa.west,
917 gl.name AS locality, gl.nameLocal AS localityLocal,
918 gs.name AS subAdministrativeArea, gs.nameLocal AS subAdministrativeAreaLocal,
919 ga.name AS administrativeArea, ga.nameLocal AS administrativeAreaLocal,
921 FROM profile_addresses AS pa
922 LEFT JOIN geoloc_localities AS gl ON (gl.id = pa.localityId)
923 LEFT JOIN geoloc_administrativeareas AS ga ON (ga.id = pa.administrativeAreaId)
924 LEFT JOIN geoloc_subadministrativeareas AS gs ON (gs.id = pa.subAdministrativeAreaId)
925 LEFT JOIN geoloc_countries AS gc ON (gc.iso_3166_1_a2 = pa.countryId)
926 ' . ((count($where) > 0) ?
'WHERE ' . implode(' AND ', $where) : '') . '
927 ORDER BY pa.pid, pa.jobid, pa.id';
928 $this->dbiter
= XDB
::iterator($sql);
931 public function next()
933 if (is_null($this->dbiter
)) {
936 $data = $this->dbiter
->next();
937 if (is_null($data)) {
940 // Adds phones to addresses.
941 $it = Phone
::iterate(array($data['pid']), array(Phone
::LINK_ADDRESS
), array($data['id']));
942 while ($phone = $it->next()) {
943 $data['phones'][$phone->id
] = $phone->toFormArray();
945 return new Address($data);
948 public function total()
950 return $this->dbiter
->total();
953 public function first()
955 return $this->dbiter
->first();
958 public function last()
960 return $this->dbiter
->last();
963 public function value()
965 return $this->dbiter
;
969 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: