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
;
300 public $postalText = '';
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 = '';
314 // Database's field required for both 'home' and 'job' addresses.
317 // Database's fields required for 'home' addresses.
318 public $flags = null
; // 'current', 'temporary', 'secondary', 'mail', 'cedex', 'deliveryIssue'
319 public $comment = null
;
320 public $current = null
;
321 public $temporary = null
;
322 public $secondary = null
;
324 public $deliveryIssue = null
;
326 // Remaining fields that do not belong to profile_addresses.
327 public $phones = array();
328 public $error = false
;
332 public function __construct(array $data = array())
334 if (count($data) > 0) {
335 foreach ($data as $key => $val) {
340 if (!is_null($this->flags
)) {
341 $this->flags
= new PlFlagSet($this->flags
);
343 static $flags = array('current', 'temporary', 'secondary', 'mail', 'deliveryIssue');
345 $this->flags
= new PlFlagSet();
346 foreach ($flags as $flag) {
347 if (!is_null($this->$flag) && ($this->$flag == 1 ||
$this->$flag == 'on')) {
348 $this->flags
->addFlag($flag, 1);
351 $this->flags
->addFlag('cedex', (strpos(strtoupper(preg_replace(array("/[0-9,\"'#~:;_\- ]/", "/\r\n/"),
352 array('', "\n"), $this->text
)), 'CEDEX')) !== false
);
357 public function setId($id)
362 public function phones()
364 return $this->phones
;
367 public function addPhone(Phone
$phone)
369 if ($phone->link_type
== Phone
::LINK_ADDRESS
&& $phone->pid
== $this->pid
) {
370 $this->phones
[$phone->uniqueId()] = $phone;
374 public function hasFlag($flag)
376 return ($this->flags
!= null
&& $this->flags
->hasFlag($flag));
379 public function addFlag($flag)
381 $this->flags
->addFlag($flag);
384 /** Auxilary function for formatting postal addresses.
385 * If the needle is found in the haystack, it notifies the substitution's
386 * success, modifies the length accordingly and returns either the matching
387 * substitution or the needle.
389 private function substitute($needle, $haystack, &$length, &$success, $trim = false
)
391 if (array_key_exists($needle, $haystack)) {
393 $length -= (strlen($needle) - strlen($haystack[$needle]));
394 return $haystack[$needle];
397 if (strlen($needle) > 4) {
398 $length -= (strlen($needle) - 4);
399 $needle = $needle{4};
405 /** Checks if the line corresponds to a French street line.
406 * A line is considered a French street line if it starts by between 1 and 4 numbers.
408 private function isStreetFR($line)
410 return preg_match('/^\d{1,4}\D/', $line);
413 /** Retrieves a French street number and slit the rest of the line into an array.
414 * @param $words: array containing the rest of the line (a word per cell).
415 * @param $line: line to consider.
416 * Returns the street number.
418 private function getStreetNumberFR(&$line)
420 // First we define numbers and separators.
421 $numberReq = '(\d{1,4})\s*(BIS|TER|QUATER|[A-Z])?';
422 $separatorReq = '\s*(?:\\|-|&|A|ET)?\s*';
424 // Then we retrieve the number(s) and the rest of the line.
425 // $matches contains:
426 // -0: the full patern, here the given line,
428 // -2: its optionnal quantifier,
429 // -3: an optionnal second number,
430 // -4: the second number's optionnal quantifier,
431 // -5: the rest of the line.
432 preg_match('/^' . $numberReq . '(?:' . $separatorReq . $numberReq . ')?\s+(.*)/', $line, $matches);
433 $number = $matches[1];
436 // If there is a precision on the address, we concatenate it to the number.
437 if ($matches[2] != '') {
438 $number .= $matches[2]{0};
439 } elseif ($matches[4] != '') {
440 $number .= $matches[4]{0};
446 /** Checks if the line corresponds to a French locality line.
447 * A line is considered a French locality line if it starts by exactly a
448 * postal code of exactly 5 numbers.
450 private function isLocalityFR($line)
452 return preg_match('/^\d{5}\D/', $line);
455 /** Retrieves a French postal code and slit the rest of the line into an array.
456 * @param $words: array containing the rest of the line (a word per cell).
457 * @param $line: line to consider.
458 * Returns the postal code, and cuts it out from the line.
460 private function getPostalCodeFR(&$line)
462 $number = substr($line, 0, 5);
463 $line = trim(substr($line, 5));
467 /** Returns the address formated for French postal use (cf AFNOR XPZ 10-011).
468 * A postal addresse containts at most 6 lines of at most 38 characters each:
469 * - addressee's identification ("MONSIEUR JEAN DURAND", "DURAND SA"…),
470 * - delivery point identification ("CHEZ TOTO APPARTEMENT 2", "SERVICE ACHAT"…),
471 * - building localisation complement ("ENTREE A BATIMENT DES JONQUILLES", "ZONE INDUSTRIELLE OUEST"…),
472 * - N° and street name ("25 RUE DES FLEURS", "LES VIGNES"…),
473 * - delivery service, street localisation complement ("BP 40122", "BP 40112 AREYRES"…),
474 * - postal code and locality or cedex code and cedex ("33500 LIBOURNE", "33506 LIBOURNE CEDEX"…).
475 * Punctuation must be removed, all leters must be uppercased.
476 * Both locality and street name must not take more than 32 characters.
478 * @param $arrayText: array containing the address to be formated, one
479 * address line per array line.
480 * @param $count: array size.
482 private function formatPostalAddressFR($arrayText)
484 // First removes country if any.
485 $count = count($arrayText);
486 if ($arrayText[$count - 1] == 'FRANCE') {
487 unset($arrayText[$count - 1]);
491 // All the lines must have less than 38 characters but street and
492 // locality lines whose limit is 32 characters.
493 foreach ($arrayText as $lineNumber => $line) {
494 if ($isStreetLine = $this->isStreetFR($line)) {
495 $formattedLine = $this->getStreetNumberFR($line) . ' ';
497 } elseif ($this->isLocalityFR($line)) {
498 $formattedLine = $this->getPostalCodeFR($line) . ' ';
505 $words = explode(' ', $line);
506 $count = count($words);
507 $length = $count - 1;
508 foreach ($words as $word) {
509 $length +
= strlen($word);
512 // Checks is length is ok. Otherwise, we try to shorten words and
513 // update the length of the current line accordingly.
514 for ($i = 0; $i < $count && $length > $limit; ++
$i) {
517 $sub = $this->substitute($words[$i], Address
::$streetAbbreviations, $length, $success, ($i == 0));
519 // Entreprises' substitution are only suitable for the first two lines.
520 if ($lineNumber <= 2 && !$success) {
521 $sub = $this->substitute($words[$i], Address
::$entrepriseAbbreviations, $length, $success);
524 $sub = $this->substitute($words[$i], Address
::$otherAbbreviations, $length, $success);
527 $formattedLine .= $sub . ' ';
529 for (; $i < $count; ++
$i) {
530 $formattedLine .= $words[$i] . ' ';
532 $arrayText[$lineNumber] = trim($formattedLine);
535 return implode("\n", $arrayText);
538 // Formats postal addresses.
539 // First erases punctuation, accents… Then uppercase the address and finally
540 // calls the country's dedicated formatting function.
541 public function formatPostalAddress()
543 // Performs rough formatting.
544 $text = mb_strtoupper(replace_accent($this->text
));
545 $text = str_replace(array(',', ';', '.', ':', '!', '?', '"', '«', '»'), '', $text);
546 $text = preg_replace('/( |\t)+/', ' ', $text);
547 $arrayText = explode("\n", $text);
548 $arrayText = array_map('trim', $arrayText);
550 // Formats according to country rules. Thus we first identify the
551 // country, then apply corresponding formatting or translate country
552 // into default language.
553 $count = count($arrayText);
554 list($countryId, $country) = XDB
::fetchOneRow('SELECT gc.iso_3166_1_a2, gc.country
555 FROM geoloc_countries AS gc
556 INNER JOIN geoloc_languages AS gl ON (gc.iso_3166_1_a2 = gl.iso_3166_1_a2)
557 WHERE gl.countryPlain = {?} OR gc.countryPlain = {?}',
558 $arrayText[$count - 1], $arrayText[$count - 1]);
559 if (is_null($countryId)) {
560 $text = $this->formatPostalAddressFR($arrayText);
561 } elseif (in_array(strtoupper($countryId), Address
::$formattings)) {
562 $text = call_user_func(array($this, 'formatPostalAddress' . strtoupper($countryId)), $arrayText);
564 $arrayText[$count - 1] = mb_strtoupper(replace_accent($country));
565 $text = implode("\n", $arrayText);
568 $this->postalText
= $text;
571 public function format()
573 $this->text
= trim($this->text
);
574 $this->phones
= Phone
::formatFormArray($this->phones
, $this->error
, new ProfileVisibility($this->pub
));
575 if ($this->removed
== 1) {
576 if (!S
::user()->checkPerms('directory_private') && Phone
::hasPrivate($this->phones
)) {
577 Platal
::page()->trigWarning("L'adresse ne peut être supprimée car elle contient des informations pour lesquelles vous n'avez le droit d'édition.");
584 $this->formatPostalAddress();
585 if ($this->changed
== 1) {
586 $gmapsGeocoder = new GMapsGeocoder();
587 $gmapsGeocoder->getGeocodedAddress($this);
590 $componants = array();
591 foreach ($this->components
as $component) {
592 $componants[] = Geocoder
::getComponentId($component);
594 $this->componentsIds
= implode(',', $componants);
599 public function toFormArray()
602 'text' => $this->text
,
603 'postalText' => $this->postalText
,
604 'types' => $this->types
,
605 'formatted_address' => $this->formatted_address
,
606 'latitude' => $this->latitude
,
607 'longitude' => $this->longitude
,
608 'southwest_latitude' => $this->southwest_latitude
,
609 'southwest_longitude' => $this->southwest_longitude
,
610 'northeast_latitude' => $this->northeast_latitude
,
611 'northeast_longitude' => $this->northeast_longitude
,
612 'location_type' => $this->location_type
,
613 'partial_match' => $this->partial_match
,
614 'componentsIds' => $this->componentsIds
617 if ($this->type
== self
::LINK_PROFILE ||
$this->type
== self
::LINK_JOB
) {
618 $address['pub'] = $this->pub
;
620 if ($this->type
== self
::LINK_PROFILE
) {
621 static $flags = array('current', 'temporary', 'secondary', 'mail', 'cedex', 'deliveryIssue');
622 foreach ($flags as $flag) {
623 $address[$flag] = $this->flags
->hasFlag($flag);
625 $address['comment'] = $this->comment
;
626 $address['phones'] = Phone
::formatFormArray($this->phones
);
632 private function toString()
634 $address = $this->text
;
635 if ($this->type
== self
::LINK_PROFILE ||
$this->type
== self
::LINK_JOB
) {
636 static $pubs = array('public' => 'publique', 'ax' => 'annuaire AX', 'private' => 'privé');
637 $address .= ' (affichage ' . $pubs[$this->pub
];
639 if ($this->type
== self
::LINK_PROFILE
) {
640 static $flags = array(
641 'current' => 'actuelle',
642 'temporary' => 'temporaire',
643 'secondary' => 'secondaire',
644 'mail' => 'conctactable par courier',
645 'deliveryIssue' => 'n\'habite pas à l\'adresse indiquée',
646 'cedex' => 'type cédex',
649 if (!$this->flags
->hasFlag('temporary')) {
650 $address .= ', permanente';
652 if (!$this->flags
->hasFlag('secondary')) {
653 $address .= ', principale';
655 foreach ($flags as $flag => $flagName) {
656 if ($this->flags
->hasFlag($flag)) {
657 $address .= ', ' . $flagName;
660 if ($this->comment
) {
661 $address .= ', commentaire : ' . $this->comment
;
663 if ($phones = Phone
::formArrayToString($this->phones
)) {
664 $address .= ', ' . $phones;
666 } elseif ($this->type
== self
::LINK_JOB
) {
672 private function isEmpty()
674 return (!$this->text ||
$this->text
== '');
677 public function save()
679 if (!$this->isEmpty()) {
680 XDB
::execute('INSERT IGNORE INTO profile_addresses (pid, jobid, groupid, type, id, flags, text, postalText, pub, comment,
681 types, formatted_address, location_type, partial_match, latitude, longitude,
682 southwest_latitude, southwest_longitude, northeast_latitude, northeast_longitude)
683 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?},
684 {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?})',
685 $this->pid
, $this->jobid
, $this->groupid
, $this->type
, $this->id
, $this->flags
, $this->text
, $this->postalText
, $this->pub
, $this->comment
,
686 $this->types
, $this->formatted_address
, $this->location_type
, $this->partial_match
, $this->latitude
, $this->longitude
,
687 $this->southwest_latitude
, $this->southwest_longitude
, $this->northeast_latitude
, $this->northeast_longitude
);
689 if ($this->componentsIds
) {
690 foreach (explode(',', $this->componentsIds
) as $component_id) {
691 XDB
::execute('INSERT IGNORE INTO profile_addresses_components (pid, jobid, groupid, type, id, component_id)
692 VALUES ({?}, {?}, {?}, {?}, {?}, {?})',
693 $this->pid
, $this->jobid
, $this->groupid
, $this->type
, $this->id
, $component_id);
697 if ($this->type
== self
::LINK_PROFILE
) {
698 Phone
::savePhones($this->phones
, $this->pid
, Phone
::LINK_ADDRESS
, $this->id
);
703 public function delete()
705 XDB
::execute('DELETE FROM profile_addresses
706 WHERE pid = {?} AND jobid = {?} AND groupid = {?} AND type = {?} AND id = {?}',
707 $this->pid
, $this->jobid
, $this->groupid
, $this->type
, $this->id
);
710 static public function deleteAddresses($pid, $type, $jobid = null
, $groupid = null
, $deletePrivate = true
)
713 if (!is_null($pid)) {
714 $where = XDB
::format(' AND pid = {?}', $pid);
716 if (!is_null($jobid)) {
717 $where = XDB
::format(' AND jobid = {?}', $jobid);
719 if (!is_null($groupid)) {
720 $where = XDB
::format(' AND groupid = {?}', $groupid);
722 XDB
::execute('DELETE FROM profile_addresses
723 WHERE type = {?}' . $where . (($deletePrivate) ?
'' : ' AND pub IN (\'public\', \'ax\')'),
725 if ($type == self
::LINK_PROFILE
) {
726 Phone
::deletePhones($pid, Phone
::LINK_ADDRESS
, null
, $deletePrivate);
730 /** Saves addresses into the database.
731 * @param $data: an array of form formatted addresses.
732 * @param $pid, $type, $linkid: pid, type and id concerned by the update.
734 static public function saveFromArray(array $data, $pid, $type = self
::LINK_PROFILE
, $linkid = null
, $savePrivate = true
)
736 foreach ($data as $id => $value) {
737 if ($value['pub'] != 'private' ||
$savePrivate) {
738 if (!is_null($linkid)) {
739 $value['id'] = $linkid;
743 if (!is_null($pid)) {
744 $value['pid'] = $pid;
746 if (!is_null($type)) {
747 $value['type'] = $type;
749 $address = new Address($value);
755 static private function formArrayWalk(array $data, $function, &$success = true
, $requiresEmptyAddress = false
)
757 $addresses = array();
758 foreach ($data as $item) {
759 $address = new Address($item);
760 $success = ($address->format() && $success);
761 if (!$address->isEmpty()) {
762 $addresses[] = call_user_func(array($address, $function));
765 if (count($address) == 0 && $requiresEmptyAddress) {
766 $address = new Address();
767 $addresses[] = call_user_func(array($address, $function));
772 // Compares two addresses. First sort by publicity, then place primary
773 // addresses before secondary addresses.
774 static private function compare(array $a, array $b)
776 $value = ProfileVisibility
::comparePublicity($a, $b);
778 if ($a['secondary'] != $b['secondary']) {
779 $value = $a['secondary'] ?
1 : -1;
785 // Formats an array of form addresses into an array of form formatted addresses.
786 static public function formatFormArray(array $data, &$success = true
)
788 $addresses = self
::formArrayWalk($data, 'toFormArray', $success, true
);
790 // Only a single address can be the profile's current address and she must have one.
792 foreach ($addresses as $key => &$address) {
793 if (isset($address['current']) && $address['current']) {
795 $address['current'] = false
;
801 if (!$hasCurrent && count($value) > 0) {
802 foreach ($value as &$address) {
803 $address['current'] = true
;
808 usort($addresses, 'Address::compare');
812 static public function formArrayToString(array $data)
814 return implode(', ', self
::formArrayWalk($data, 'toString'));
817 static public function hasPrivate(array $addresses)
819 foreach ($addresses as $address) {
820 if ($address['pub'] == 'private') {
827 static public function iterate(array $pids = array(), array $types = array(),
828 array $jobids = array(), array $pubs = array())
830 return new AddressIterator($pids, $types, $jobids, $pubs);
834 /** Iterator over a set of Phones
836 * @param $pid, $type, $jobid, $pub
838 * The iterator contains the phones that correspond to the value stored in the
839 * parameters' arrays.
841 class AddressIterator
implements PlIterator
845 public function __construct(array $pids, array $types, array $jobids, array $pubs)
848 if (count($pids) != 0) {
849 $where[] = XDB
::format('(pa.pid IN {?})', $pids);
851 if (count($types) != 0) {
852 $where[] = XDB
::format('(pa.type IN {?})', $types);
854 if (count($jobids) != 0) {
855 $where[] = XDB
::format('(pa.jobid IN {?})', $jobids);
857 if (count($pubs) != 0) {
858 $where[] = XDB
::format('(pa.pub IN {?})', $pubs);
860 $sql = 'SELECT pa.pid, pa.jobid, pa.groupid, pa.type, pa.id, pa.flags, pa.text, pa.postalText, pa.pub, pa.comment,
861 pa.types, pa.formatted_address, pa.location_type, pa.partial_match, pa.latitude, pa.longitude,
862 pa.southwest_latitude, pa.southwest_longitude, pa.northeast_latitude, pa.northeast_longitude,
863 GROUP_CONCAT(DISTINCT pc.component_id SEPARATOR \',\') AS componentsIds
864 FROM profile_addresses AS pa
865 LEFT JOIN profile_addresses_components AS pc ON (pa.pid = pc.pid AND pa.jobid = pc.jobid AND pa.groupid = pc.groupid
866 AND pa.type = pc.type AND pa.id = pc.id)
867 ' . ((count($where) > 0) ?
'WHERE ' . implode(' AND ', $where) : '') . '
868 GROUP BY pa.pid, pa.jobid, pa.groupid, pa.type, pa.id
869 ORDER BY pa.pid, pa.jobid, pa.id';
870 $this->dbiter
= XDB
::iterator($sql);
873 public function next()
875 if (is_null($this->dbiter
)) {
878 $data = $this->dbiter
->next();
879 if (is_null($data)) {
882 // Adds phones to addresses.
883 $it = Phone
::iterate(array($data['pid']), array(Phone
::LINK_ADDRESS
), array($data['id']));
884 while ($phone = $it->next()) {
885 $data['phones'][$phone->id
] = $phone->toFormArray();
887 return new Address($data);
890 public function total()
892 return $this->dbiter
->total();
895 public function first()
897 return $this->dbiter
->first();
900 public function last()
902 return $this->dbiter
->last();
905 public function value()
907 return $this->dbiter
;
911 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: