e5f677c35c96e9abc182ab0d0f6b3fb9e8e534f8
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 = '';
301 public $postal_code_fr = null
;
303 public $formatted_address = '';
304 public $components = array();
305 public $latitude = null
;
306 public $longitude = null
;
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 = '';
314 public $request = false
;
315 public $geocoding_date = null
;
316 public $geocoding_calls = 0;
318 // Database's field required for both 'home' and 'job' addresses.
321 // Database's fields required for 'home' addresses.
322 public $flags = null
; // 'current', 'temporary', 'secondary', 'mail', 'cedex', 'deliveryIssue'
323 public $comment = null
;
324 public $current = null
;
325 public $temporary = null
;
326 public $secondary = null
;
328 public $deliveryIssue = null
;
330 // Remaining fields that do not belong to profile_addresses.
331 public $phones = array();
332 public $error = false
;
336 public function __construct(array $data = array())
338 if (count($data) > 0) {
339 foreach ($data as $key => $val) {
344 if (!is_null($this->flags
)) {
345 $this->flags
= new PlFlagSet($this->flags
);
347 static $flags = array('current', 'temporary', 'secondary', 'mail', 'deliveryIssue');
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);
355 $this->flags
->addFlag('cedex', (strpos(strtoupper(preg_replace(array("/[0-9,\"'#~:;_\- ]/", "/\r\n/"),
356 array('', "\n"), $this->text
)), 'CEDEX')) !== false
);
359 $this->request
= ($this->request ||
!is_null(AddressReq
::get_request($this->pid
, $this->jobid
, $this->groupid
, $this->type
, $this->id
)));
362 public function setId($id)
367 public function phones()
369 return $this->phones
;
372 public function addPhone(Phone
$phone)
374 if ($phone->link_type
== Phone
::LINK_ADDRESS
&& $phone->pid
== $this->pid
) {
375 $this->phones
[$phone->uniqueId()] = $phone;
379 public function hasFlag($flag)
381 return ($this->flags
!= null
&& $this->flags
->hasFlag($flag));
384 public function addFlag($flag)
386 $this->flags
->addFlag($flag);
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.
394 private function substitute($needle, $haystack, &$length, &$success, $trim = false
)
396 if (array_key_exists($needle, $haystack)) {
398 $length -= (strlen($needle) - strlen($haystack[$needle]));
399 return $haystack[$needle];
402 if (strlen($needle) > 4) {
403 $length -= (strlen($needle) - 4);
404 $needle = $needle{4};
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.
413 private function isStreetFR($line)
415 return preg_match('/^\d{1,4}\D/', $line);
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.
423 private function getStreetNumberFR(&$line)
425 // First we define numbers and separators.
426 $numberReq = '(\d{1,4})\s*(BIS|TER|QUATER|[A-Z])?';
427 $separatorReq = '\s*(?:\\\\|\/|-|&|A|ET)?\s*';
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,
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);
438 $number = $matches[1];
441 // If there is a precision on the address, we concatenate it to the number.
442 if ($matches[2] != '') {
443 $number .= $matches[2]{0};
444 } elseif ($matches[4] != '') {
445 $number .= $matches[4]{0};
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.
455 private function isLocalityFR($line)
457 return preg_match('/^\d{5}\D/', $line);
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.
465 private function getPostalCodeFR(&$line)
467 $number = substr($line, 0, 5);
468 $line = trim(substr($line, 5));
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.
483 * @param $arrayText: array containing the address to be formated, one
484 * address line per array line.
485 * @param $count: array size.
487 private function formatPostalAddressFR($arrayText)
489 // First removes country if any.
490 $count = count($arrayText);
491 if ($arrayText[$count - 1] == 'FRANCE') {
492 unset($arrayText[$count - 1]);
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) . ' ';
503 } elseif ($this->isLocalityFR($line)) {
504 $postal_code = $this->getPostalCodeFR($line);
505 $formattedLine = $postal_code . ' ';
512 $words = explode(' ', $line);
513 $count = count($words);
514 $length = $count - 1;
515 foreach ($words as $word) {
516 $length +
= strlen($word);
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) {
524 $sub = $this->substitute($words[$i], Address
::$streetAbbreviations, $length, $success, ($i == 0));
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);
531 $sub = $this->substitute($words[$i], Address
::$otherAbbreviations, $length, $success);
534 $formattedLine .= $sub . ' ';
536 for (; $i < $count; ++
$i) {
537 $formattedLine .= $words[$i] . ' ';
539 $arrayText[$lineNumber] = trim($formattedLine);
542 $this->postal_code_fr
= $postal_code;
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 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);
572 $arrayText[$count - 1] = mb_strtoupper(replace_accent($country));
573 $text = implode("\n", $arrayText);
576 $this->postalText
= $text;
579 public function format()
581 $this->text
= trim($this->text
);
582 $this->phones
= Phone
::formatFormArray($this->phones
, $this->error
, $this->pub
);
583 if ($this->removed
== 1) {
584 if (!S
::user()->checkPerms('directory_private') && Phone
::hasPrivate($this->phones
)) {
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.");
592 $this->formatPostalAddress();
593 if ($this->changed
== 1) {
594 $gmapsGeocoder = new GMapsGeocoder();
595 $gmapsGeocoder->getGeocodedAddress($this);
597 $componants = array();
598 foreach ($this->components
as $component) {
599 $componants[] = Geocoder
::getComponentId($component);
601 $this->componentsIds
= implode(',', $componants);
603 if ($this->componentsIds
== '') {
604 $this->latitude
= null
;
605 $this->longitude
= null
;
611 public function toFormArray()
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
,
626 'componentsIds' => $this->componentsIds
,
627 'geocoding_date' => $this->geocoding_date
,
628 'geocoding_calls' => $this->geocoding_calls
,
629 'request' => $this->request
632 if ($this->type
== self
::LINK_JOB
) {
633 $address['pub'] = $this->pub
;
634 $address['mail'] = $this->flags
->hasFlag('mail');
636 if ($this->type
== self
::LINK_PROFILE
) {
637 static $flags = array('current', 'temporary', 'secondary', 'mail', 'cedex', 'deliveryIssue');
638 foreach ($flags as $flag) {
639 $address[$flag] = $this->flags
->hasFlag($flag);
641 $address['pub'] = $this->pub
;
642 $address['comment'] = $this->comment
;
643 $address['phones'] = Phone
::formatFormArray($this->phones
);
649 private function toString()
651 $address = $this->text
;
652 if ($this->type
== self
::LINK_PROFILE ||
$this->type
== self
::LINK_JOB
) {
653 static $pubs = array('public' => 'publique', 'ax' => 'annuaire AX', 'private' => 'privé');
654 $address .= ' (affichage ' . $pubs[$this->pub
];
656 if ($this->type
== self
::LINK_PROFILE
) {
657 static $flags = array(
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',
666 if (!$this->flags
->hasFlag('temporary')) {
667 $address .= ', permanente';
669 if (!$this->flags
->hasFlag('secondary')) {
670 $address .= ', principale';
672 foreach ($flags as $flag => $flagName) {
673 if ($this->flags
->hasFlag($flag)) {
674 $address .= ', ' . $flagName;
677 if ($this->comment
) {
678 $address .= ', commentaire : ' . $this->comment
;
680 if ($phones = Phone
::formArrayToString($this->phones
)) {
681 $address .= ', ' . $phones;
683 } elseif ($this->type
== self
::LINK_JOB
) {
689 private function isEmpty()
691 return (!$this->text ||
$this->text
== '');
694 public function save($notify_ungeocoded = true
)
696 if (!$this->isEmpty()) {
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,
699 southwest_latitude, southwest_longitude, northeast_latitude, northeast_longitude,
700 geocoding_date, geocoding_calls, postal_code_fr)
701 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?},
702 {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, NOW(), {?}, {?})',
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
,
705 $this->southwest_latitude
, $this->southwest_longitude
, $this->northeast_latitude
, $this->northeast_longitude
, $this->geocoding_calls
, $this->postal_code_fr
);
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);
713 } elseif ($notify_ungeocoded) {
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
);
721 if ($this->type
== self
::LINK_PROFILE
) {
722 Phone
::savePhones($this->phones
, $this->pid
, Phone
::LINK_ADDRESS
, $this->id
);
725 if ($this->request
) {
726 $req = new AddressReq(S
::user(), $this->toFormArray(), $this->pid
, $this->jobid
, $this->groupid
, $this->type
, $this->id
);
732 public function updateGeocoding($text)
734 XDB
::execute('UPDATE profile_addresses
735 SET text = {?}, postalText = {?}, types = {?}, formatted_address = {?},
736 location_type = {?}, partial_match = {?}, latitude = {?}, longitude = {?},
737 southwest_latitude = {?}, southwest_longitude = {?}, northeast_latitude = {?}, northeast_longitude = {?},
738 geocoding_date = NOW(), geocoding_calls = {?}
739 WHERE pid = {?} AND jobid = {?} AND groupid = {?} AND type = {?} AND id = {?}',
740 $this->text
, $this->postalText
, $this->types
, $this->formatted_address
,
741 $this->location_type
, $this->partial_match
, $this->latitude
, $this->longitude
,
742 $this->southwest_latitude
, $this->southwest_longitude
, $this->northeast_latitude
, $this->northeast_longitude
, $this->geocoding_calls
,
743 $this->pid
, $this->jobid
, $this->groupid
, $this->type
, $this->id
);
745 XDB
::execute('DELETE FROM profile_addresses_components
746 WHERE pid = {?} AND jobid = {?} AND groupid = {?} AND type = {?} AND id = {?}',
747 $this->pid
, $this->jobid
, $this->groupid
, $this->type
, $this->id
);
748 if ($this->componentsIds
) {
749 foreach (explode(',', $this->componentsIds
) as $component_id) {
750 XDB
::execute('INSERT IGNORE INTO profile_addresses_components (pid, jobid, groupid, type, id, component_id)
751 VALUES ({?}, {?}, {?}, {?}, {?}, {?})',
752 $this->pid
, $this->jobid
, $this->groupid
, $this->type
, $this->id
, $component_id);
757 public function delete()
759 XDB
::execute('DELETE FROM profile_addresses_components
760 WHERE pid = {?} AND jobid = {?} AND groupid = {?} AND type = {?} AND id = {?}',
761 $this->pid
, $this->jobid
, $this->groupid
, $this->type
, $this->id
);
762 XDB
::execute('DELETE FROM profile_addresses
763 WHERE pid = {?} AND jobid = {?} AND groupid = {?} AND type = {?} AND id = {?}',
764 $this->pid
, $this->jobid
, $this->groupid
, $this->type
, $this->id
);
766 return XDB
::affectedRows();
769 static public function deleteAddresses($pid, $type, $jobid = null
, $groupid = null
, $deletePrivate = true
)
772 if (!is_null($pid)) {
773 $where = XDB
::format(' AND pid = {?}', $pid);
775 if (!is_null($jobid)) {
776 $where = XDB
::format(' AND jobid = {?}', $jobid);
778 if (!is_null($groupid)) {
779 $where = XDB
::format(' AND groupid = {?}', $groupid);
781 XDB
::execute('DELETE FROM profile_addresses
782 WHERE type = {?}' . $where . (($deletePrivate) ?
'' : ' AND pub IN (\'public\', \'ax\')'),
784 if ($type == self
::LINK_PROFILE
) {
785 Phone
::deletePhones($pid, Phone
::LINK_ADDRESS
, null
, $deletePrivate);
789 /** Saves addresses into the database.
790 * @param $data: an array of form formatted addresses.
791 * @param $pid, $type, $linkid: pid, type and id concerned by the update.
793 static public function saveFromArray(array $data, $pid, $type = self
::LINK_PROFILE
, $linkid = null
, $savePrivate = true
)
795 foreach ($data as $id => $value) {
796 if ($value['pub'] != 'private' ||
$savePrivate) {
797 if (!is_null($linkid)) {
798 $value['id'] = $linkid;
802 if (!is_null($pid)) {
803 $value['pid'] = $pid;
805 if (!is_null($type)) {
806 $value['type'] = $type;
808 $address = new Address($value);
814 static private function formArrayWalk(array $data, $function, &$success = true
, $requiresEmptyAddress = false
)
816 $addresses = array();
817 foreach ($data as $item) {
818 $address = new Address($item);
819 $success = ($address->format() && $success);
820 if (!$address->isEmpty()) {
821 $addresses[] = call_user_func(array($address, $function));
824 if (count($address) == 0 && $requiresEmptyAddress) {
825 $address = new Address();
826 $addresses[] = call_user_func(array($address, $function));
831 // Compares two addresses. First sort by publicity, then place primary
832 // addresses before secondary addresses.
833 static private function compare(array $a, array $b)
835 $value = Visibility
::comparePublicity($a, $b);
837 if ($a['secondary'] != $b['secondary']) {
838 $value = $a['secondary'] ?
1 : -1;
844 // Formats an array of form addresses into an array of form formatted addresses.
845 static public function formatFormArray(array $data, &$success = true
)
847 $addresses = self
::formArrayWalk($data, 'toFormArray', $success, true
);
849 // Only a single address can be the profile's current address and she must have one.
851 foreach ($addresses as $key => &$address) {
852 if (isset($address['current']) && $address['current']) {
854 $address['current'] = false
;
860 if (!$hasCurrent && count($value) > 0) {
861 foreach ($value as &$address) {
862 $address['current'] = true
;
867 usort($addresses, 'Address::compare');
871 static public function formArrayToString(array $data)
873 return implode(', ', self
::formArrayWalk($data, 'toString'));
876 static public function hasPrivate(array $addresses)
878 foreach ($addresses as $address) {
879 if ($address['pub'] == 'private') {
886 static public function iterate(array $pids = array(), array $types = array(),
887 array $jobids = array(), $visibility = null
, $where = null
)
889 return new AddressIterator($pids, $types, $jobids, $visibility, $where);
893 /** Iterator over a set of Phones
895 * @param $pid, $type, $jobid, $pub
897 * The iterator contains the phones that correspond to the value stored in the
898 * parameters' arrays.
900 class AddressIterator
implements PlIterator
905 public function __construct(array $pids, array $types, array $jobids, $visibility, $_where)
908 if (!is_null($_where)) {
911 if (count($pids) != 0) {
912 $where[] = XDB
::format('(pa.pid IN {?})', $pids);
914 if (count($types) != 0) {
915 $where[] = XDB
::format('(pa.type IN {?})', $types);
917 if (count($jobids) != 0) {
918 $where[] = XDB
::format('(pa.jobid IN {?})', $jobids);
920 if ($visibility == null ||
!($visibility instanceof Visibility
)) {
921 $visibility = Visibility
::defaultForRead();
923 $where[] = 'pve.best_display_level+0 <= pa.pub+0';
925 $sql = 'SELECT pa.pid, pa.jobid, pa.groupid, pa.type, pa.id, pa.flags, pa.text, pa.postalText, pa.pub, pa.comment,
926 pa.types, pa.formatted_address, pa.location_type, pa.partial_match, pa.latitude, pa.longitude,
927 pa.southwest_latitude, pa.southwest_longitude, pa.northeast_latitude, pa.northeast_longitude,
928 pa.geocoding_date, pa.geocoding_calls,
929 GROUP_CONCAT(DISTINCT pc.component_id SEPARATOR \',\') AS componentsIds,
930 GROUP_CONCAT(pace1.long_name) AS postalCode, GROUP_CONCAT(pace2.long_name) AS locality,
931 GROUP_CONCAT(pace3.long_name) AS administrativeArea, GROUP_CONCAT(pace4.long_name) AS country
932 FROM profile_addresses AS pa
933 LEFT JOIN profile_addresses_components AS pc ON (pa.pid = pc.pid AND pa.jobid = pc.jobid AND pa.groupid = pc.groupid
934 AND pa.type = pc.type AND pa.id = pc.id)
935 LEFT JOIN profile_addresses_components_enum AS pace1 ON (FIND_IN_SET(\'postal_code\', pace1.types) AND pace1.id = pc.component_id)
936 LEFT JOIN profile_addresses_components_enum AS pace2 ON (FIND_IN_SET(\'locality\', pace2.types) AND pace2.id = pc.component_id)
937 LEFT JOIN profile_addresses_components_enum AS pace3 ON (FIND_IN_SET(\'administrative_area_level_1\', pace3.types) AND pace3.id = pc.component_id)
938 LEFT JOIN profile_addresses_components_enum AS pace4 ON (FIND_IN_SET(\'country\', pace4.types) AND pace4.id = pc.component_id)
939 LEFT JOIN profile_visibility_enum AS pve ON (pve.access_level = {?})
940 WHERE ' . implode(' AND ', $where) . '
941 GROUP BY pa.pid, pa.jobid, pa.groupid, pa.type, pa.id
942 ORDER BY pa.pid, pa.jobid, pa.id';
943 $this->dbiter
= XDB
::iterator($sql, $visibility->level());
944 $this->visibility
= $visibility;
947 public function next()
949 if (is_null($this->dbiter
)) {
952 $data = $this->dbiter
->next();
953 if (is_null($data)) {
956 // Adds phones to addresses.
957 $it = Phone
::iterate(array($data['pid']), array(Phone
::LINK_ADDRESS
), array($data['id']), $this->visibility
);
958 while ($phone = $it->next()) {
959 $data['phones'][$phone->id
] = $phone->toFormArray();
961 return new Address($data);
964 public function total()
966 return $this->dbiter
->total();
969 public function first()
971 return $this->dbiter
->first();
974 public function last()
976 return $this->dbiter
->last();
979 public function value()
981 return $this->dbiter
;
985 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: