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 = '';
313 public $request = false
;
314 public $geocoding_date = null
;
315 public $geocoding_calls = 0;
317 // Database's field required for both 'home' and 'job' addresses.
320 // Database's fields required for 'home' addresses.
321 public $flags = null
; // 'current', 'temporary', 'secondary', 'mail', 'cedex', 'deliveryIssue'
322 public $comment = null
;
323 public $current = null
;
324 public $temporary = null
;
325 public $secondary = null
;
327 public $deliveryIssue = null
;
329 // Remaining fields that do not belong to profile_addresses.
330 public $phones = array();
331 public $error = false
;
335 public function __construct(array $data = array())
337 if (count($data) > 0) {
338 foreach ($data as $key => $val) {
343 if (!is_null($this->flags
)) {
344 $this->flags
= new PlFlagSet($this->flags
);
346 static $flags = array('current', 'temporary', 'secondary', 'mail', 'deliveryIssue');
348 $this->flags
= new PlFlagSet();
349 foreach ($flags as $flag) {
350 if (!is_null($this->$flag) && ($this->$flag == 1 ||
$this->$flag == 'on')) {
351 $this->flags
->addFlag($flag, 1);
354 $this->flags
->addFlag('cedex', (strpos(strtoupper(preg_replace(array("/[0-9,\"'#~:;_\- ]/", "/\r\n/"),
355 array('', "\n"), $this->text
)), 'CEDEX')) !== false
);
358 $this->request
= ($this->request ||
!is_null(AddressReq
::get_request($this->pid
, $this->jobid
, $this->groupid
, $this->type
, $this->id
)));
361 public function setId($id)
366 public function phones()
368 return $this->phones
;
371 public function addPhone(Phone
$phone)
373 if ($phone->link_type
== Phone
::LINK_ADDRESS
&& $phone->pid
== $this->pid
) {
374 $this->phones
[$phone->uniqueId()] = $phone;
378 public function hasFlag($flag)
380 return ($this->flags
!= null
&& $this->flags
->hasFlag($flag));
383 public function addFlag($flag)
385 $this->flags
->addFlag($flag);
388 /** Auxilary function for formatting postal addresses.
389 * If the needle is found in the haystack, it notifies the substitution's
390 * success, modifies the length accordingly and returns either the matching
391 * substitution or the needle.
393 private function substitute($needle, $haystack, &$length, &$success, $trim = false
)
395 if (array_key_exists($needle, $haystack)) {
397 $length -= (strlen($needle) - strlen($haystack[$needle]));
398 return $haystack[$needle];
401 if (strlen($needle) > 4) {
402 $length -= (strlen($needle) - 4);
403 $needle = $needle{4};
409 /** Checks if the line corresponds to a French street line.
410 * A line is considered a French street line if it starts by between 1 and 4 numbers.
412 private function isStreetFR($line)
414 return preg_match('/^\d{1,4}\D/', $line);
417 /** Retrieves a French street number and slit the rest of the line into an array.
418 * @param $words: array containing the rest of the line (a word per cell).
419 * @param $line: line to consider.
420 * Returns the street number.
422 private function getStreetNumberFR(&$line)
424 // First we define numbers and separators.
425 $numberReq = '(\d{1,4})\s*(BIS|TER|QUATER|[A-Z])?';
426 $separatorReq = '\s*(?:\\|-|&|A|ET)?\s*';
428 // Then we retrieve the number(s) and the rest of the line.
429 // $matches contains:
430 // -0: the full patern, here the given line,
432 // -2: its optionnal quantifier,
433 // -3: an optionnal second number,
434 // -4: the second number's optionnal quantifier,
435 // -5: the rest of the line.
436 preg_match('/^' . $numberReq . '(?:' . $separatorReq . $numberReq . ')?\s+(.*)/', $line, $matches);
437 $number = $matches[1];
440 // If there is a precision on the address, we concatenate it to the number.
441 if ($matches[2] != '') {
442 $number .= $matches[2]{0};
443 } elseif ($matches[4] != '') {
444 $number .= $matches[4]{0};
450 /** Checks if the line corresponds to a French locality line.
451 * A line is considered a French locality line if it starts by exactly a
452 * postal code of exactly 5 numbers.
454 private function isLocalityFR($line)
456 return preg_match('/^\d{5}\D/', $line);
459 /** Retrieves a French postal code and slit the rest of the line into an array.
460 * @param $words: array containing the rest of the line (a word per cell).
461 * @param $line: line to consider.
462 * Returns the postal code, and cuts it out from the line.
464 private function getPostalCodeFR(&$line)
466 $number = substr($line, 0, 5);
467 $line = trim(substr($line, 5));
471 /** Returns the address formated for French postal use (cf AFNOR XPZ 10-011).
472 * A postal addresse containts at most 6 lines of at most 38 characters each:
473 * - addressee's identification ("MONSIEUR JEAN DURAND", "DURAND SA"…),
474 * - delivery point identification ("CHEZ TOTO APPARTEMENT 2", "SERVICE ACHAT"…),
475 * - building localisation complement ("ENTREE A BATIMENT DES JONQUILLES", "ZONE INDUSTRIELLE OUEST"…),
476 * - N° and street name ("25 RUE DES FLEURS", "LES VIGNES"…),
477 * - delivery service, street localisation complement ("BP 40122", "BP 40112 AREYRES"…),
478 * - postal code and locality or cedex code and cedex ("33500 LIBOURNE", "33506 LIBOURNE CEDEX"…).
479 * Punctuation must be removed, all leters must be uppercased.
480 * Both locality and street name must not take more than 32 characters.
482 * @param $arrayText: array containing the address to be formated, one
483 * address line per array line.
484 * @param $count: array size.
486 private function formatPostalAddressFR($arrayText)
488 // First removes country if any.
489 $count = count($arrayText);
490 if ($arrayText[$count - 1] == 'FRANCE') {
491 unset($arrayText[$count - 1]);
495 // All the lines must have less than 38 characters but street and
496 // locality lines whose limit is 32 characters.
497 foreach ($arrayText as $lineNumber => $line) {
498 if ($isStreetLine = $this->isStreetFR($line)) {
499 $formattedLine = $this->getStreetNumberFR($line) . ' ';
501 } elseif ($this->isLocalityFR($line)) {
502 $formattedLine = $this->getPostalCodeFR($line) . ' ';
509 $words = explode(' ', $line);
510 $count = count($words);
511 $length = $count - 1;
512 foreach ($words as $word) {
513 $length +
= strlen($word);
516 // Checks is length is ok. Otherwise, we try to shorten words and
517 // update the length of the current line accordingly.
518 for ($i = 0; $i < $count && $length > $limit; ++
$i) {
521 $sub = $this->substitute($words[$i], Address
::$streetAbbreviations, $length, $success, ($i == 0));
523 // Entreprises' substitution are only suitable for the first two lines.
524 if ($lineNumber <= 2 && !$success) {
525 $sub = $this->substitute($words[$i], Address
::$entrepriseAbbreviations, $length, $success);
528 $sub = $this->substitute($words[$i], Address
::$otherAbbreviations, $length, $success);
531 $formattedLine .= $sub . ' ';
533 for (; $i < $count; ++
$i) {
534 $formattedLine .= $words[$i] . ' ';
536 $arrayText[$lineNumber] = trim($formattedLine);
539 return implode("\n", $arrayText);
542 // Formats postal addresses.
543 // First erases punctuation, accents… Then uppercase the address and finally
544 // calls the country's dedicated formatting function.
545 public function formatPostalAddress()
547 // Performs rough formatting.
548 $text = mb_strtoupper(replace_accent($this->text
));
549 $text = str_replace(array(',', ';', '.', ':', '!', '?', '"', '«', '»'), '', $text);
550 $text = preg_replace('/( |\t)+/', ' ', $text);
551 $arrayText = explode("\n", $text);
552 $arrayText = array_map('trim', $arrayText);
554 // Formats according to country rules. Thus we first identify the
555 // country, then apply corresponding formatting or translate country
556 // into default language.
557 $count = count($arrayText);
558 list($countryId, $country) = XDB
::fetchOneRow('SELECT gc.iso_3166_1_a2, gc.country
559 FROM geoloc_countries AS gc
560 INNER JOIN geoloc_languages AS gl ON (gc.iso_3166_1_a2 = gl.iso_3166_1_a2)
561 WHERE gl.countryPlain = {?} OR gc.countryPlain = {?}',
562 $arrayText[$count - 1], $arrayText[$count - 1]);
563 if (is_null($countryId)) {
564 $text = $this->formatPostalAddressFR($arrayText);
565 } elseif (in_array(strtoupper($countryId), Address
::$formattings)) {
566 $text = call_user_func(array($this, 'formatPostalAddress' . strtoupper($countryId)), $arrayText);
568 $arrayText[$count - 1] = mb_strtoupper(replace_accent($country));
569 $text = implode("\n", $arrayText);
572 $this->postalText
= $text;
575 public function format()
577 $this->text
= trim($this->text
);
578 $this->phones
= Phone
::formatFormArray($this->phones
, $this->error
, $this->pub
);
579 if ($this->removed
== 1) {
580 if (!S
::user()->checkPerms('directory_private') && Phone
::hasPrivate($this->phones
)) {
581 Platal
::page()->trigWarning("L'adresse ne peut être supprimée car elle contient des informations pour lesquelles vous n'avez le droit d'édition.");
588 $this->formatPostalAddress();
589 if ($this->changed
== 1) {
590 $gmapsGeocoder = new GMapsGeocoder();
591 $gmapsGeocoder->getGeocodedAddress($this);
593 $componants = array();
594 foreach ($this->components
as $component) {
595 $componants[] = Geocoder
::getComponentId($component);
597 $this->componentsIds
= implode(',', $componants);
599 if ($this->componentsIds
== '') {
600 $this->latitude
= null
;
601 $this->longitude
= null
;
607 public function toFormArray()
610 'text' => $this->text
,
611 'postalText' => $this->postalText
,
612 'types' => $this->types
,
613 'formatted_address' => $this->formatted_address
,
614 'latitude' => $this->latitude
,
615 'longitude' => $this->longitude
,
616 'southwest_latitude' => $this->southwest_latitude
,
617 'southwest_longitude' => $this->southwest_longitude
,
618 'northeast_latitude' => $this->northeast_latitude
,
619 'northeast_longitude' => $this->northeast_longitude
,
620 'location_type' => $this->location_type
,
621 'partial_match' => $this->partial_match
,
622 'componentsIds' => $this->componentsIds
,
623 'geocoding_date' => $this->geocoding_date
,
624 'geocoding_calls' => $this->geocoding_calls
,
625 'request' => $this->request
628 if ($this->type
== self
::LINK_JOB
) {
629 $address['pub'] = $this->pub
;
630 $address['mail'] = $this->flags
->hasFlag('mail');
632 if ($this->type
== self
::LINK_PROFILE
) {
633 static $flags = array('current', 'temporary', 'secondary', 'mail', 'cedex', 'deliveryIssue');
634 foreach ($flags as $flag) {
635 $address[$flag] = $this->flags
->hasFlag($flag);
637 $address['pub'] = $this->pub
;
638 $address['comment'] = $this->comment
;
639 $address['phones'] = Phone
::formatFormArray($this->phones
);
645 private function toString()
647 $address = $this->text
;
648 if ($this->type
== self
::LINK_PROFILE ||
$this->type
== self
::LINK_JOB
) {
649 static $pubs = array('public' => 'publique', 'ax' => 'annuaire AX', 'private' => 'privé');
650 $address .= ' (affichage ' . $pubs[$this->pub
];
652 if ($this->type
== self
::LINK_PROFILE
) {
653 static $flags = array(
654 'current' => 'actuelle',
655 'temporary' => 'temporaire',
656 'secondary' => 'secondaire',
657 'mail' => 'conctactable par courier',
658 'deliveryIssue' => 'n\'habite pas à l\'adresse indiquée',
659 'cedex' => 'type cédex',
662 if (!$this->flags
->hasFlag('temporary')) {
663 $address .= ', permanente';
665 if (!$this->flags
->hasFlag('secondary')) {
666 $address .= ', principale';
668 foreach ($flags as $flag => $flagName) {
669 if ($this->flags
->hasFlag($flag)) {
670 $address .= ', ' . $flagName;
673 if ($this->comment
) {
674 $address .= ', commentaire : ' . $this->comment
;
676 if ($phones = Phone
::formArrayToString($this->phones
)) {
677 $address .= ', ' . $phones;
679 } elseif ($this->type
== self
::LINK_JOB
) {
685 private function isEmpty()
687 return (!$this->text ||
$this->text
== '');
690 public function save($notify_ungeocoded = true
)
692 if (!$this->isEmpty()) {
693 XDB
::execute('INSERT IGNORE INTO profile_addresses (pid, jobid, groupid, type, id, flags, text, postalText, pub, comment,
694 types, formatted_address, location_type, partial_match, latitude, longitude,
695 southwest_latitude, southwest_longitude, northeast_latitude, northeast_longitude,
696 geocoding_date, geocoding_calls)
697 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?},
698 {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, NOW(), {?})',
699 $this->pid
, $this->jobid
, $this->groupid
, $this->type
, $this->id
, $this->flags
, $this->text
, $this->postalText
, $this->pub
, $this->comment
,
700 $this->types
, $this->formatted_address
, $this->location_type
, $this->partial_match
, $this->latitude
, $this->longitude
,
701 $this->southwest_latitude
, $this->southwest_longitude
, $this->northeast_latitude
, $this->northeast_longitude
, $this->geocoding_calls
);
703 if ($this->componentsIds
) {
704 foreach (explode(',', $this->componentsIds
) as $component_id) {
705 XDB
::execute('INSERT IGNORE INTO profile_addresses_components (pid, jobid, groupid, type, id, component_id)
706 VALUES ({?}, {?}, {?}, {?}, {?}, {?})',
707 $this->pid
, $this->jobid
, $this->groupid
, $this->type
, $this->id
, $component_id);
709 } elseif ($notify_ungeocoded) {
710 // If the address was not geocoded, notifies it to the appropriate ML.
711 $mailer = new PlMailer('profile/no_geocoding.mail.tpl');
712 $mailer->assign('text', $this->text
);
713 $mailer->assign('primary_key', $this->pid
. '-' . $this->jobid
. '-' . $this->groupid
. '-' . $this->type
. '-' . $this->id
);
717 if ($this->type
== self
::LINK_PROFILE
) {
718 Phone
::savePhones($this->phones
, $this->pid
, Phone
::LINK_ADDRESS
, $this->id
);
721 if ($this->request
) {
722 $req = new AddressReq(S
::user(), $this->toFormArray(), $this->pid
, $this->jobid
, $this->groupid
, $this->type
, $this->id
);
728 public function updateGeocoding($text)
730 XDB
::execute('UPDATE profile_addresses
731 SET text = {?}, postalText = {?}, types = {?}, formatted_address = {?},
732 location_type = {?}, partial_match = {?}, latitude = {?}, longitude = {?},
733 southwest_latitude = {?}, southwest_longitude = {?}, northeast_latitude = {?}, northeast_longitude = {?},
734 geocoding_date = NOW(), geocoding_calls = {?}
735 WHERE pid = {?} AND jobid = {?} AND groupid = {?} AND type = {?} AND id = {?}',
736 $this->text
, $this->postalText
, $this->types
, $this->formatted_address
,
737 $this->location_type
, $this->partial_match
, $this->latitude
, $this->longitude
,
738 $this->southwest_latitude
, $this->southwest_longitude
, $this->northeast_latitude
, $this->northeast_longitude
, $this->geocoding_calls
,
739 $this->pid
, $this->jobid
, $this->groupid
, $this->type
, $this->id
);
741 XDB
::execute('DELETE FROM profile_addresses_components
742 WHERE pid = {?} AND jobid = {?} AND groupid = {?} AND type = {?} AND id = {?}',
743 $this->pid
, $this->jobid
, $this->groupid
, $this->type
, $this->id
);
744 if ($this->componentsIds
) {
745 foreach (explode(',', $this->componentsIds
) as $component_id) {
746 XDB
::execute('INSERT IGNORE INTO profile_addresses_components (pid, jobid, groupid, type, id, component_id)
747 VALUES ({?}, {?}, {?}, {?}, {?}, {?})',
748 $this->pid
, $this->jobid
, $this->groupid
, $this->type
, $this->id
, $component_id);
753 public function delete()
755 XDB
::execute('DELETE FROM profile_addresses_components
756 WHERE pid = {?} AND jobid = {?} AND groupid = {?} AND type = {?} AND id = {?}',
757 $this->pid
, $this->jobid
, $this->groupid
, $this->type
, $this->id
);
758 XDB
::execute('DELETE FROM profile_addresses
759 WHERE pid = {?} AND jobid = {?} AND groupid = {?} AND type = {?} AND id = {?}',
760 $this->pid
, $this->jobid
, $this->groupid
, $this->type
, $this->id
);
762 return XDB
::affectedRows();
765 static public function deleteAddresses($pid, $type, $jobid = null
, $groupid = null
, $deletePrivate = true
)
768 if (!is_null($pid)) {
769 $where = XDB
::format(' AND pid = {?}', $pid);
771 if (!is_null($jobid)) {
772 $where = XDB
::format(' AND jobid = {?}', $jobid);
774 if (!is_null($groupid)) {
775 $where = XDB
::format(' AND groupid = {?}', $groupid);
777 XDB
::execute('DELETE FROM profile_addresses
778 WHERE type = {?}' . $where . (($deletePrivate) ?
'' : ' AND pub IN (\'public\', \'ax\')'),
780 if ($type == self
::LINK_PROFILE
) {
781 Phone
::deletePhones($pid, Phone
::LINK_ADDRESS
, null
, $deletePrivate);
785 /** Saves addresses into the database.
786 * @param $data: an array of form formatted addresses.
787 * @param $pid, $type, $linkid: pid, type and id concerned by the update.
789 static public function saveFromArray(array $data, $pid, $type = self
::LINK_PROFILE
, $linkid = null
, $savePrivate = true
)
791 foreach ($data as $id => $value) {
792 if ($value['pub'] != 'private' ||
$savePrivate) {
793 if (!is_null($linkid)) {
794 $value['id'] = $linkid;
798 if (!is_null($pid)) {
799 $value['pid'] = $pid;
801 if (!is_null($type)) {
802 $value['type'] = $type;
804 $address = new Address($value);
810 static private function formArrayWalk(array $data, $function, &$success = true
, $requiresEmptyAddress = false
)
812 $addresses = array();
813 foreach ($data as $item) {
814 $address = new Address($item);
815 $success = ($address->format() && $success);
816 if (!$address->isEmpty()) {
817 $addresses[] = call_user_func(array($address, $function));
820 if (count($address) == 0 && $requiresEmptyAddress) {
821 $address = new Address();
822 $addresses[] = call_user_func(array($address, $function));
827 // Compares two addresses. First sort by publicity, then place primary
828 // addresses before secondary addresses.
829 static private function compare(array $a, array $b)
831 $value = Visibility
::comparePublicity($a, $b);
833 if ($a['secondary'] != $b['secondary']) {
834 $value = $a['secondary'] ?
1 : -1;
840 // Formats an array of form addresses into an array of form formatted addresses.
841 static public function formatFormArray(array $data, &$success = true
)
843 $addresses = self
::formArrayWalk($data, 'toFormArray', $success, true
);
845 // Only a single address can be the profile's current address and she must have one.
847 foreach ($addresses as $key => &$address) {
848 if (isset($address['current']) && $address['current']) {
850 $address['current'] = false
;
856 if (!$hasCurrent && count($value) > 0) {
857 foreach ($value as &$address) {
858 $address['current'] = true
;
863 usort($addresses, 'Address::compare');
867 static public function formArrayToString(array $data)
869 return implode(', ', self
::formArrayWalk($data, 'toString'));
872 static public function hasPrivate(array $addresses)
874 foreach ($addresses as $address) {
875 if ($address['pub'] == 'private') {
882 static public function iterate(array $pids = array(), array $types = array(),
883 array $jobids = array(), $visibility = null
, $where = null
)
885 return new AddressIterator($pids, $types, $jobids, $visibility, $where);
889 /** Iterator over a set of Phones
891 * @param $pid, $type, $jobid, $pub
893 * The iterator contains the phones that correspond to the value stored in the
894 * parameters' arrays.
896 class AddressIterator
implements PlIterator
901 public function __construct(array $pids, array $types, array $jobids, $visibility, $_where)
904 if (!is_null($_where)) {
907 if (count($pids) != 0) {
908 $where[] = XDB
::format('(pa.pid IN {?})', $pids);
910 if (count($types) != 0) {
911 $where[] = XDB
::format('(pa.type IN {?})', $types);
913 if (count($jobids) != 0) {
914 $where[] = XDB
::format('(pa.jobid IN {?})', $jobids);
916 if ($visibility == null ||
!($visibility instanceof Visibility
)) {
917 $visibility = Visibility
::defaultForRead();
919 $where[] = 'pve.best_display_level+0 <= pa.pub+0';
921 $sql = 'SELECT pa.pid, pa.jobid, pa.groupid, pa.type, pa.id, pa.flags, pa.text, pa.postalText, pa.pub, pa.comment,
922 pa.types, pa.formatted_address, pa.location_type, pa.partial_match, pa.latitude, pa.longitude,
923 pa.southwest_latitude, pa.southwest_longitude, pa.northeast_latitude, pa.northeast_longitude,
924 pa.geocoding_date, pa.geocoding_calls,
925 GROUP_CONCAT(DISTINCT pc.component_id SEPARATOR \',\') AS componentsIds,
926 GROUP_CONCAT(pace1.long_name) AS postalCode, GROUP_CONCAT(pace2.long_name) AS locality,
927 GROUP_CONCAT(pace3.long_name) AS administrativeArea, GROUP_CONCAT(pace4.long_name) AS country
928 FROM profile_addresses AS pa
929 LEFT JOIN profile_addresses_components AS pc ON (pa.pid = pc.pid AND pa.jobid = pc.jobid AND pa.groupid = pc.groupid
930 AND pa.type = pc.type AND pa.id = pc.id)
931 LEFT JOIN profile_addresses_components_enum AS pace1 ON (FIND_IN_SET(\'postal_code\', pace1.types) AND pace1.id = pc.component_id)
932 LEFT JOIN profile_addresses_components_enum AS pace2 ON (FIND_IN_SET(\'locality\', pace2.types) AND pace2.id = pc.component_id)
933 LEFT JOIN profile_addresses_components_enum AS pace3 ON (FIND_IN_SET(\'administrative_area_level_1\', pace3.types) AND pace3.id = pc.component_id)
934 LEFT JOIN profile_addresses_components_enum AS pace4 ON (FIND_IN_SET(\'country\', pace4.types) AND pace4.id = pc.component_id)
935 LEFT JOIN profile_visibility_enum AS pve ON (pve.access_level = {?})
936 WHERE ' . implode(' AND ', $where) . '
937 GROUP BY pa.pid, pa.jobid, pa.groupid, pa.type, pa.id
938 ORDER BY pa.pid, pa.jobid, pa.id';
939 $this->dbiter
= XDB
::iterator($sql, $visibility->level());
940 $this->visibility
= $visibility;
943 public function next()
945 if (is_null($this->dbiter
)) {
948 $data = $this->dbiter
->next();
949 if (is_null($data)) {
952 // Adds phones to addresses.
953 $it = Phone
::iterate(array($data['pid']), array(Phone
::LINK_ADDRESS
), array($data['id']), $this->visibility
);
954 while ($phone = $it->next()) {
955 $data['phones'][$phone->id
] = $phone->toFormArray();
957 return new Address($data);
960 public function total()
962 return $this->dbiter
->total();
965 public function first()
967 return $this->dbiter
->first();
970 public function last()
972 return $this->dbiter
->last();
975 public function value()
977 return $this->dbiter
;
981 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: