Add 'hidden' flag to text descriptions of the 'pub' flag
[platal.git] / classes / address.php
index 70e7354..cffa45b 100644 (file)
@@ -1,6 +1,6 @@
 <?php
 /***************************************************************************
- *  Copyright (C) 2003-2010 Polytechnique.org                              *
+ *  Copyright (C) 2003-2014 Polytechnique.org                              *
  *  http://opensource.polytechnique.org/                                   *
  *                                                                         *
  *  This program is free software; you can redistribute it and/or modify   *
  *   - `id` is the id of the job to which we refer (in profile_job)
  *   - `jobid` is set to 0
  *
+ * - for a Group:
+ *  - `type` is set to 'group'
+ *  - `pid` is set to 0
+ *  - `jobid` is set to 0
+ *  - `groupid` is set to the group id
+ *
  * Thus an Address can be linked to a Company, a Profile, or a Job.
  */
 class Address
@@ -48,6 +54,7 @@ class Address
     const LINK_JOB     = 'job';
     const LINK_COMPANY = 'hq';
     const LINK_PROFILE = 'home';
+    const LINK_GROUP   = 'group';
 
     // List of all available postal formattings.
     private static $formattings = array('FRANCE' => 'FR');
@@ -284,29 +291,29 @@ class Address
     // Primary key fields: the quadruplet ($pid, $jobid, $type, $id) defines a unique address.
     public $pid = 0;
     public $jobid = 0;
+    public $groupid = 0;
     public $type = Address::LINK_PROFILE;
     public $id = 0;
 
     // Geocoding fields.
-    public $accuracy = 0;
     public $text = '';
     public $postalText = '';
-    public $postalCode = null;
-    public $localityId = null;
-    public $subAdministrativeAreaId = null;
-    public $administrativeAreaId = null;
-    public $localityName = null;
-    public $subAdministrativeAreaName = null;
-    public $administrativeAreaName = null;
-    public $countryId = null;
+    public $postal_code_fr = null;
+    public $types = '';
+    public $formatted_address = '';
+    public $components = array();
     public $latitude = null;
     public $longitude = null;
-    public $north = null;
-    public $south = null;
-    public $east = null;
-    public $west = null;
-    public $geocodedText = null;
-    public $geocodeChosen = null;
+    public $southwest_latitude = null;
+    public $southwest_longitude = null;
+    public $northeast_latitude = null;
+    public $northeast_longitude = null;
+    public $location_type = '';
+    public $partial_match = false;
+    public $componentsIds = '';
+    public $request = false;
+    public $geocoding_date = null;
+    public $geocoding_calls = 0;
 
     // Database's field required for both 'home' and 'job' addresses.
     public $pub = 'ax';
@@ -349,6 +356,7 @@ class Address
                                                                                array('', "\n"), $this->text)), 'CEDEX')) !== false);
             }
         }
+        $this->request = ($this->request || !is_null(AddressReq::get_request($this->pid, $this->jobid, $this->groupid, $this->type, $this->id)));
     }
 
     public function setId($id)
@@ -361,9 +369,9 @@ class Address
         return $this->phones;
     }
 
-    public function addPhone(Phone &$phone)
+    public function addPhone(Phone $phone)
     {
-        if ($phone->linkType() == Phone::LINK_ADDRESS && $phone->pid() == $this->pid) {
+        if ($phone->link_type == Phone::LINK_ADDRESS && $phone->pid == $this->pid) {
             $this->phones[$phone->uniqueId()] = $phone;
         }
     }
@@ -416,7 +424,7 @@ class Address
     {
         // First we define numbers and separators.
         $numberReq = '(\d{1,4})\s*(BIS|TER|QUATER|[A-Z])?';
-        $separatorReq = '\s*(?:\\|-|&|A|ET)?\s*';
+        $separatorReq = '\s*(?:\\\\|\/|-|&|A|ET)?\s*';
 
         // Then we retrieve the number(s) and the rest of the line.
         // $matches contains:
@@ -485,6 +493,7 @@ class Address
             --$count;
         }
 
+        $postal_code = null;
         // All the lines must have less than 38 characters but street and
         // locality lines whose limit is 32 characters.
         foreach ($arrayText as $lineNumber => $line) {
@@ -492,7 +501,8 @@ class Address
                 $formattedLine = $this->getStreetNumberFR($line) . ' ';
                 $limit = 32;
             } elseif ($this->isLocalityFR($line)) {
-                $formattedLine = $this->getPostalCodeFR($line) . ' ';
+                $postal_code = $this->getPostalCodeFR($line);
+                $formattedLine = $postal_code . ' ';
                 $limit = 32;
             } else {
                 $formattedLine = '';
@@ -529,6 +539,7 @@ class Address
             $arrayText[$lineNumber] = trim($formattedLine);
         }
 
+        $this->postal_code_fr = $postal_code;
         return implode("\n", $arrayText);
     }
 
@@ -544,106 +555,90 @@ class Address
         $arrayText = explode("\n", $text);
         $arrayText = array_map('trim', $arrayText);
 
-        // Search for country.
-        $countries = DirEnum::getOptions(DirEnum::COUNTRIES);
-        $countries = array_map('replace_accent', $countries);
-        $countries = array_map('strtoupper', $countries);
+        // Formats according to country rules. Thus we first identify the
+        // country, then apply corresponding formatting or translate country
+        // into default language.
         $count = count($arrayText);
-        if (in_array(strtoupper($this->countryId), Address::$formattings)) {
-            $text = call_user_func(array($this, 'formatPostalAddress' . strtoupper($this->countryId)), $arrayText);
-        } elseif (array_key_exists($arrayText[$count - 1], Address::$formattings)) {
-            $text = call_user_func(array($this, 'formatPostalAddress' . Address::$formattings[$arrayText[$count - 1]]), $arrayText);
-        } elseif (!in_array($arrayText[$count - 1], $countries)) {
+        list($countryId, $country) = XDB::fetchOneRow('SELECT  gc.iso_3166_1_a2, gc.country
+                                                         FROM  geoloc_countries AS gc
+                                                   INNER JOIN  geoloc_languages AS gl ON (gc.iso_3166_1_a2 = gl.iso_3166_1_a2)
+                                                        WHERE  gl.countryPlain = {?} OR gc.countryPlain = {?}',
+                                                      $arrayText[$count - 1], $arrayText[$count - 1]);
+        if (is_null($countryId)) {
             $text = $this->formatPostalAddressFR($arrayText);
+        } elseif (in_array(strtoupper($countryId), Address::$formattings)) {
+            $text = call_user_func(array($this, 'formatPostalAddress' . strtoupper($countryId)), $arrayText);
         } else {
+            $arrayText[$count - 1] = mb_strtoupper(replace_accent($country));
             $text = implode("\n", $arrayText);
         }
 
         $this->postalText = $text;
     }
 
-    public function format(array $format = array())
+    public function format()
     {
-        if (empty($format)) {
-            $format['requireGeocoding'] = false;
-            $format['stripGeocoding'] = false;
-            $format['postalText'] = false;
-        } else {
-            foreach (array('requireGeocoding', 'stripGeocoding', 'postalText') as $type) {
-                $format[$type] = (isset($format[$type])) ? $format[$type] : false;
-            }
-        }
         $this->text = trim($this->text);
+        $this->phones = Phone::formatFormArray($this->phones, $this->error, $this->pub);
         if ($this->removed == 1) {
-            $this->text = '';
-            return true;
+            if (!S::user()->checkPerms('directory_private') && Phone::hasPrivate($this->phones)) {
+                Platal::page()->trigWarning("L'adresse ne peut être supprimée car elle contient des informations pour lesquelles vous n'avez le droit d'édition.");
+            } else  {
+                $this->text = '';
+                return true;
+            }
         }
 
-        if ($format['requireGeocoding'] || $this->changed == 1) {
+        $this->formatPostalAddress();
+        if ($this->changed == 1) {
             $gmapsGeocoder = new GMapsGeocoder();
             $gmapsGeocoder->getGeocodedAddress($this);
-            $this->changed = 0;
-            $this->error = !empty($this->geocodedText);
-        }
-        if ($format['stripGeocoding'] || ($this->type == self::LINK_COMPANY && $this->error) || $this->geocodeChosen === '0') {
-            $gmapsGeocoder = new GMapsGeocoder();
-            $gmapsGeocoder->stripGeocodingFromAddress($this);
-            if ($this->geocodeChosen === '0') {
-                $mailer = new PlMailer('profile/geocoding.mail.tpl');
-                $mailer->assign('text', $this->text);
-                $mailer->assign('geoloc', $this->geocodedText);
-                $mailer->send();
+
+            $componants = array();
+            foreach ($this->components as $component) {
+                $componants[] = Geocoder::getComponentId($component);
             }
+            $this->componentsIds = implode(',', $componants);
         }
-        if ($this->countryId == '') {
-            $this->countryId = null;
+        if ($this->componentsIds == '') {
+            $this->latitude = null;
+            $this->longitude = null;
         }
-        $this->geocodeChosen = null;
-        $this->phones = Phone::formatFormArray($this->phones, $this->error, new ProfileVisibility($this->pub));
-        if ($format['postalText']) {
-            $this->formatPostalAddress();
-        }
-        return !$this->error;
+
+        return true;
     }
 
     public function toFormArray()
     {
         $address = array(
-            'accuracy'                  => $this->accuracy,
-            'text'                      => $this->text,
-            'postalText'                => $this->postalText,
-            'postalCode'                => $this->postalCode,
-            'localityId'                => $this->localityId,
-            'subAdministrativeAreaId'   => $this->subAdministrativeAreaId,
-            'administrativeAreaId'      => $this->administrativeAreaId,
-            'countryId'                 => $this->countryId,
-            'localityName'              => $this->localityName,
-            'subAdministrativeAreaName' => $this->subAdministrativeAreaName,
-            'administrativeAreaName'    => $this->administrativeAreaName,
-            'latitude'                  => $this->latitude,
-            'longitude'                 => $this->longitude,
-            'north'                     => $this->north,
-            'south'                     => $this->south,
-            'east'                      => $this->east,
-            'west'                      => $this->west,
-            'error'                     => $this->error,
-            'changed'                   => $this->changed,
-            'removed'                   => $this->removed,
+            'text'                => $this->text,
+            'postalText'          => $this->postalText,
+            'types'               => $this->types,
+            'formatted_address'   => $this->formatted_address,
+            'latitude'            => $this->latitude,
+            'longitude'           => $this->longitude,
+            'southwest_latitude'  => $this->southwest_latitude,
+            'southwest_longitude' => $this->southwest_longitude,
+            'northeast_latitude'  => $this->northeast_latitude,
+            'northeast_longitude' => $this->northeast_longitude,
+            'location_type'       => $this->location_type,
+            'partial_match'       => $this->partial_match,
+            'componentsIds'       => $this->componentsIds,
+            'geocoding_date'      => $this->geocoding_date,
+            'geocoding_calls'     => $this->geocoding_calls,
+            'request'             => $this->request
         );
-        if (!is_null($this->geocodedText)) {
-            $address['geocodedText'] = $this->geocodedText;
-            $address['geocodeChosen'] = $this->geocodeChosen;
-        }
 
-        if ($this->type == self::LINK_PROFILE || $this->type == self::LINK_JOB) {
-            $address['pub'] = $this->pub;
+        if ($this->type == self::LINK_JOB) {
+            $address['pub']  = $this->pub;
+            $address['mail'] = $this->flags->hasFlag('mail');
         }
         if ($this->type == self::LINK_PROFILE) {
             static $flags = array('current', 'temporary', 'secondary', 'mail', 'cedex', 'deliveryIssue');
-
             foreach ($flags as $flag) {
                 $address[$flag] = $this->flags->hasFlag($flag);
             }
+            $address['pub']     = $this->pub;
             $address['comment'] = $this->comment;
             $address['phones']  = Phone::formatFormArray($this->phones);
         }
@@ -655,7 +650,7 @@ class Address
     {
         $address = $this->text;
         if ($this->type == self::LINK_PROFILE || $this->type == self::LINK_JOB) {
-            static $pubs = array('public' => 'publique', 'ax' => 'annuaire AX', 'private' => 'privé');
+            static $pubs = array('public' => 'publique', 'ax' => 'annuaire papier', 'private' => 'privé', 'hidden' => 'administrateurs');
             $address .= ' (affichage ' . $pubs[$this->pub];
         }
         if ($this->type == self::LINK_PROFILE) {
@@ -696,44 +691,129 @@ class Address
         return (!$this->text || $this->text == '');
     }
 
-    public function save()
+    public function save($notify_ungeocoded = true)
     {
-        static $areas = array('administrativeArea', 'subAdministrativeArea', 'locality');
-
-        $this->format(array('postalText' => true));
         if (!$this->isEmpty()) {
-            foreach ($areas as $area) {
-                Geocoder::getAreaId($this, $area);
-            }
+            XDB::execute('INSERT IGNORE INTO  profile_addresses (pid, jobid, groupid, type, id, flags, text, postalText, pub, comment,
+                                                                 types, formatted_address, location_type, partial_match, latitude, longitude,
+                                                                 southwest_latitude, southwest_longitude, northeast_latitude, northeast_longitude,
+                                                                 geocoding_date, geocoding_calls, postal_code_fr)
+                                      VALUES  ({?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?},
+                                               {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, NOW(), {?}, {?})',
+                         $this->pid, $this->jobid, $this->groupid, $this->type, $this->id, $this->flags, $this->text, $this->postalText, $this->pub, $this->comment,
+                         $this->types, $this->formatted_address, $this->location_type, $this->partial_match, $this->latitude, $this->longitude,
+                         $this->southwest_latitude, $this->southwest_longitude, $this->northeast_latitude, $this->northeast_longitude, $this->geocoding_calls, $this->postal_code_fr);
 
-            XDB::execute('INSERT INTO  profile_addresses (pid, jobid, type, id, flags, accuracy,
-                                                          text, postalText, postalCode, localityId,
-                                                          subAdministrativeAreaId, administrativeAreaId,
-                                                          countryId, latitude, longitude, pub, comment,
-                                                          north, south, east, west)
-                               VALUES  ({?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?},
-                                        {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?})',
-                         $this->pid, $this->jobid, $this->type, $this->id, $this->flags, $this->accuracy,
-                         $this->text, $this->postalText, $this->postalCode, $this->localityId,
-                         $this->subAdministrativeAreaId, $this->administrativeAreaId,
-                         $this->countryId, $this->latitude, $this->longitude,
-                         $this->pub, $this->comment,
-                         $this->north, $this->south, $this->east, $this->west);
+            if ($this->componentsIds) {
+                foreach (explode(',', $this->componentsIds) as $component_id) {
+                    XDB::execute('INSERT IGNORE INTO  profile_addresses_components (pid, jobid, groupid, type, id, component_id)
+                                              VALUES  ({?}, {?}, {?}, {?}, {?}, {?})',
+                                 $this->pid, $this->jobid, $this->groupid, $this->type, $this->id, $component_id);
+                }
+            } elseif ($notify_ungeocoded) {
+                // If the address was not geocoded, notifies it to the appropriate ML.
+                $mailer = new PlMailer('profile/no_geocoding.mail.tpl');
+                $mailer->assign('text', $this->text);
+                $mailer->assign('primary_key', $this->pid . '-' . $this->jobid . '-' . $this->groupid . '-' . $this->type . '-' . $this->id);
+                $mailer->send();
+            }
 
             if ($this->type == self::LINK_PROFILE) {
                 Phone::savePhones($this->phones, $this->pid, Phone::LINK_ADDRESS, $this->id);
             }
+
+            if ($this->request) {
+                $req = new AddressReq(S::user(), $this->toFormArray(), $this->pid, $this->jobid, $this->groupid, $this->type, $this->id);
+                $req->submit();
+            }
+
+            if ($this->pid != 0) {
+                self::updateBestMail($this->pid);
+            }
+        }
+    }
+
+    /**
+     * Upate the denormalized flag which is used to mark the best mail to use
+     * when sending postal mail
+     *
+     * Call with $fake to true to only get which address would be selected,
+     * without updating anything in the database.
+     * Returns an array describing the selected profile address
+     */
+    static public function updateBestMail($pid, $fake=false)
+    {
+        if (!$fake) {
+            XDB::execute("UPDATE  profile_addresses
+                             SET  flags = REPLACE(flags, 'dn_best_mail', '')
+                           WHERE  pid = {?}",
+                         $pid);
+        }
+
+        /* Following order is selected to find the best mail:
+         *  * Use addresses without the deliveryIssue flag if possible.
+         *  * Among these, use addresses flagged as "current".
+         *  * If there is no such addresses or several ones, prefer those
+         *    without "secondary" flag.
+         *  * If there are still several addresses in the selection, try not
+         *    to select the ones with "job" type.
+         */
+        $best_mail = XDB::fetchOneAssoc("SELECT  pid, jobid, groupid, type, id, flags
+                                         FROM  profile_addresses
+                                        WHERE  FIND_IN_SET('mail', flags) AND pid = {?}
+                                     ORDER BY  FIND_IN_SET('deliveryIssue', flags),
+                                               NOT FIND_IN_SET('current', flags),
+                                               FIND_IN_SET('secondary', flags), type = 'job'
+                                        LIMIT  1",
+                                      $pid);
+
+        if (!$fake && $best_mail) {
+            XDB::execute("UPDATE  profile_addresses
+                             SET  flags = CONCAT(flags, ',dn_best_mail')
+                           WHERE  pid = {?} AND jobid = {?} AND groupid = {?} AND type = {?} AND id = {?}",
+                         $best_mail['pid'], $best_mail['jobid'], $best_mail['groupid'], $best_mail['type'], $best_mail['id']);
+        }
+        return $best_mail;
+    }
+
+    public function updateGeocoding($text)
+    {
+        XDB::execute('UPDATE  profile_addresses
+                         SET  text = {?}, postalText = {?}, types = {?}, formatted_address = {?},
+                              location_type = {?}, partial_match = {?}, latitude = {?}, longitude = {?},
+                              southwest_latitude = {?}, southwest_longitude = {?}, northeast_latitude = {?}, northeast_longitude = {?},
+                              geocoding_date = NOW(), geocoding_calls = {?}
+                       WHERE  pid = {?} AND jobid = {?} AND groupid = {?} AND type = {?} AND id = {?}',
+                     $this->text, $this->postalText, $this->types, $this->formatted_address,
+                     $this->location_type, $this->partial_match, $this->latitude, $this->longitude,
+                     $this->southwest_latitude, $this->southwest_longitude, $this->northeast_latitude, $this->northeast_longitude, $this->geocoding_calls,
+                     $this->pid, $this->jobid, $this->groupid, $this->type, $this->id);
+
+        XDB::execute('DELETE FROM  profile_addresses_components
+                            WHERE  pid = {?} AND jobid = {?} AND groupid = {?} AND type = {?} AND id = {?}',
+                     $this->pid, $this->jobid, $this->groupid, $this->type, $this->id);
+        if ($this->componentsIds) {
+            foreach (explode(',', $this->componentsIds) as $component_id) {
+                XDB::execute('INSERT IGNORE INTO  profile_addresses_components (pid, jobid, groupid, type, id, component_id)
+                                          VALUES  ({?}, {?}, {?}, {?}, {?}, {?})',
+                             $this->pid, $this->jobid, $this->groupid, $this->type, $this->id, $component_id);
+            }
         }
     }
 
     public function delete()
     {
+        XDB::execute('DELETE FROM  profile_addresses_components
+                            WHERE  pid = {?} AND jobid = {?} AND groupid = {?} AND type = {?} AND id = {?}',
+                     $this->pid, $this->jobid, $this->groupid, $this->type, $this->id);
         XDB::execute('DELETE FROM  profile_addresses
-                            WHERE  pid = {?} AND jobid = {?} AND type = {?} AND id = {?}',
-                     $this->pid, $this->jobid, $this->type, $this->id);
+                            WHERE  pid = {?} AND jobid = {?} AND groupid = {?} AND type = {?} AND id = {?}',
+                     $this->pid, $this->jobid, $this->groupid, $this->type, $this->id);
+
+        return XDB::affectedRows();
     }
 
-    static public function deleteAddresses($pid, $type, $jobid = null, $deletePrivate = true)
+    static public function deleteAddresses($pid, $type, $jobid = null, $groupid = null, $deletePrivate = true)
     {
         $where = '';
         if (!is_null($pid)) {
@@ -742,6 +822,9 @@ class Address
         if (!is_null($jobid)) {
             $where = XDB::format(' AND jobid = {?}', $jobid);
         }
+        if (!is_null($groupid)) {
+            $where = XDB::format(' AND groupid = {?}', $groupid);
+        }
         XDB::execute('DELETE FROM  profile_addresses
                             WHERE  type = {?}' . $where . (($deletePrivate) ? '' : ' AND pub IN (\'public\', \'ax\')'),
                      $type);
@@ -754,22 +837,24 @@ class Address
      * @param $data: an array of form formatted addresses.
      * @param $pid, $type, $linkid: pid, type and id concerned by the update.
      */
-    static public function saveFromArray(array $data, $pid, $type = self::LINK_PROFILE, $linkid = null)
+    static public function saveFromArray(array $data, $pid, $type = self::LINK_PROFILE, $linkid = null, $savePrivate = true)
     {
         foreach ($data as $id => $value) {
-            if (!is_null($linkid)) {
-                $value['id'] = $linkid;
-            } else {
-                $value['id'] = $id;
-            }
-            if (!is_null($pid)) {
-                $value['pid'] = $pid;
-            }
-            if (!is_null($type)) {
-                $value['type'] = $type;
+            if ($value['pub'] != 'private' || $savePrivate) {
+                if (!is_null($linkid)) {
+                    $value['id'] = $linkid;
+                } else {
+                    $value['id'] = $id;
+                }
+                if (!is_null($pid)) {
+                    $value['pid'] = $pid;
+                }
+                if (!is_null($type)) {
+                    $value['type'] = $type;
+                }
+                $address = new Address($value);
+                $address->save();
             }
-            $address = new Address($value);
-            $address->save();
         }
     }
 
@@ -790,12 +875,27 @@ class Address
         return $addresses;
     }
 
+    // Compares two addresses. First sort by publicity, then place primary
+    // addresses before secondary addresses.
+    static private function compare(array $a, array $b)
+    {
+        $value = Visibility::comparePublicity($a, $b);
+        if ($value == 0) {
+            if ($a['secondary'] != $b['secondary']) {
+                $value = $a['secondary'] ? 1 : -1;
+            }
+        }
+        return $value;
+    }
+
     // Formats an array of form addresses into an array of form formatted addresses.
     static public function formatFormArray(array $data, &$success = true)
     {
+        $addresses = self::formArrayWalk($data, 'toFormArray', $success, true);
+
         // Only a single address can be the profile's current address and she must have one.
         $hasCurrent = false;
-        foreach ($data as $key => &$address) {
+        foreach ($addresses as $key => &$address) {
             if (isset($address['current']) && $address['current']) {
                 if ($hasCurrent) {
                     $address['current'] = false;
@@ -811,7 +911,8 @@ class Address
             }
         }
 
-        return self::formArrayWalk($data, 'toFormArray', $success, true);
+        usort($addresses, 'Address::compare');
+        return $addresses;
     }
 
     static public function formArrayToString(array $data)
@@ -819,27 +920,41 @@ class Address
         return implode(', ', self::formArrayWalk($data, 'toString'));
     }
 
+    static public function hasPrivate(array $addresses)
+    {
+        foreach ($addresses as $address) {
+            if ($address['pub'] == 'private') {
+                return true;
+            }
+        }
+        return false;
+    }
+
     static public function iterate(array $pids = array(), array $types = array(),
-                                   array $jobids = array(), array $pubs = array())
+                                   array $jobids = array(), $visibility = null, $where = null)
     {
-        return new AddressIterator($pids, $types, $jobids, $pubs);
+        return new AddressIterator($pids, $types, $jobids, $visibility, $where);
     }
 }
 
-/** Iterator over a set of Phones
+/** Iterator over a set of Addresses
  *
  * @param $pid, $type, $jobid, $pub
  *
- * The iterator contains the phones that correspond to the value stored in the
- * parameters' arrays.
+ * The iterator contains the addresses that correspond to the value stored in
+ * the parameters' arrays.
  */
 class AddressIterator implements PlIterator
 {
     private $dbiter;
+    private $visibility;
 
-    public function __construct(array $pids, array $types, array $jobids, array $pubs)
+    public function __construct(array $pids, array $types, array $jobids, $visibility, $_where)
     {
         $where = array();
+        if (!is_null($_where)) {
+            $where[] = $_where;
+        }
         if (count($pids) != 0) {
             $where[] = XDB::format('(pa.pid IN {?})', $pids);
         }
@@ -849,25 +964,31 @@ class AddressIterator implements PlIterator
         if (count($jobids) != 0) {
             $where[] = XDB::format('(pa.jobid IN {?})', $jobids);
         }
-        if (count($pubs) != 0) {
-            $where[] = XDB::format('(pa.pub IN {?})', $pubs);
-        }
-        $sql = 'SELECT  pa.pid, pa.jobid, pa.type, pa.id, pa.flags,
-                        pa.accuracy, pa.text, pa.postalText, pa.postalCode,
-                        pa.localityId, pa.subAdministrativeAreaId,
-                        pa.administrativeAreaId, pa.countryId,
-                        pa.latitude, pa.longitude, pa.north, pa.south, pa.east, pa.west,
-                        pa.pub, pa.comment,
-                        gl.name AS locality, gs.name AS subAdministrativeArea,
-                        ga.name AS administrativeArea, gc.countryFR AS country
-                  FROM  profile_addresses             AS pa
-             LEFT JOIN  geoloc_localities             AS gl ON (gl.id = pa.localityId)
-             LEFT JOIN  geoloc_administrativeareas    AS ga ON (ga.id = pa.administrativeAreaId)
-             LEFT JOIN  geoloc_subadministrativeareas AS gs ON (gs.id = pa.subAdministrativeAreaId)
-             LEFT JOIN  geoloc_countries              AS gc ON (gc.iso_3166_1_a2 = pa.countryId)
-                 ' . ((count($where) > 0) ? 'WHERE  ' . implode(' AND ', $where) : '') . '
+        if ($visibility == null || !($visibility instanceof Visibility)) {
+            $visibility = Visibility::defaultForRead();
+        }
+        $where[] = 'pve.best_display_level+0 <= pa.pub+0';
+
+        $sql = 'SELECT  pa.pid, pa.jobid, pa.groupid, pa.type, pa.id, pa.flags, pa.text, pa.postalText, pa.pub, pa.comment,
+                        pa.types, pa.formatted_address, pa.location_type, pa.partial_match, pa.latitude, pa.longitude,
+                        pa.southwest_latitude, pa.southwest_longitude, pa.northeast_latitude, pa.northeast_longitude,
+                        pa.geocoding_date, pa.geocoding_calls,
+                        GROUP_CONCAT(DISTINCT pc.component_id SEPARATOR \',\') AS componentsIds,
+                        GROUP_CONCAT(pace1.long_name) AS postalCode, GROUP_CONCAT(pace2.long_name) AS locality,
+                        GROUP_CONCAT(pace3.long_name) AS administrativeArea, GROUP_CONCAT(pace4.long_name) AS country
+                  FROM  profile_addresses                 AS pa
+             LEFT JOIN  profile_addresses_components      AS pc    ON (pa.pid = pc.pid AND pa.jobid = pc.jobid AND pa.groupid = pc.groupid
+                                                                       AND pa.type = pc.type AND pa.id = pc.id)
+             LEFT JOIN  profile_addresses_components_enum AS pace1 ON (FIND_IN_SET(\'postal_code\', pace1.types) AND pace1.id = pc.component_id)
+             LEFT JOIN  profile_addresses_components_enum AS pace2 ON (FIND_IN_SET(\'locality\', pace2.types) AND pace2.id = pc.component_id)
+             LEFT JOIN  profile_addresses_components_enum AS pace3 ON (FIND_IN_SET(\'administrative_area_level_1\', pace3.types) AND pace3.id = pc.component_id)
+             LEFT JOIN  profile_addresses_components_enum AS pace4 ON (FIND_IN_SET(\'country\', pace4.types) AND pace4.id = pc.component_id)
+             LEFT JOIN  profile_visibility_enum AS pve ON (pve.access_level = {?})
+                 WHERE  ' . implode(' AND ', $where) . '
+              GROUP BY  pa.pid, pa.jobid, pa.groupid, pa.type, pa.id
               ORDER BY  pa.pid, pa.jobid, pa.id';
-        $this->dbiter = XDB::iterator($sql);
+        $this->dbiter = XDB::iterator($sql, $visibility->level());
+        $this->visibility = $visibility;
     }
 
     public function next()
@@ -880,9 +1001,9 @@ class AddressIterator implements PlIterator
             return null;
         }
         // Adds phones to addresses.
-        $it = Phone::iterate(array($data['pid']), array(Phone::LINK_ADDRESS), array($data['id']));
+        $it = Phone::iterate(array($data['pid']), array(Phone::LINK_ADDRESS), array($data['id']), $this->visibility);
         while ($phone = $it->next()) {
-            $data['phones'][$phone->id()] = $phone->toFormArray();
+            $data['phones'][$phone->id] = $phone->toFormArray();
         }
         return new Address($data);
     }
@@ -908,5 +1029,5 @@ class AddressIterator implements PlIterator
     }
 }
 
-// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
+// vim:set et sw=4 sts=4 sws=4 foldmethod=marker fenc=utf-8:
 ?>