Edits TODOs and XXXs.
[platal.git] / include / profilefields.inc.php
index 97eebaf..16b8e1e 100644 (file)
  */
 abstract class ProfileField
 {
+    public static $fields = array(
+        Profile::FETCH_ADDRESSES      => 'ProfileAddresses',
+        Profile::FETCH_CORPS          => 'ProfileCorps',
+        Profile::FETCH_EDU            => 'ProfileEducation',
+        Profile::FETCH_JOBS           => 'ProfileJobs',
+        Profile::FETCH_MEDALS         => 'ProfileMedals',
+        Profile::FETCH_NETWORKING     => 'ProfileNetworking',
+        Profile::FETCH_PHONES         => 'ProfilePhones',
+        Profile::FETCH_MENTOR_SECTOR  => 'ProfileMentoringSectors',
+        Profile::FETCH_MENTOR_COUNTRY => 'ProfileMentoringCountries',
+    );
+
     /** The profile to which this field belongs
      */
     public $pid;
@@ -34,10 +46,15 @@ abstract class ProfileField
      * @param $pids An array of pids
      * @param $visibility The level of visibility fetched fields must have
      * @return a PlIterator yielding data suitable for a "new ProfileBlah($data)"
+     *
+     * MUST be reimplemented for each kind of ProfileField.
      */
-    abstract public static function fetchData(array $pids, $visibility);
+    public static function fetchData(array $pids, ProfileVisibility $visibility)
+    {
+        return PlIteratorUtils::emptyIterator();
+    }
 
-    public static function buildForPID($cls, $pid, $visibility)
+    public static function buildForPID($cls, $pid, ProfileVisibility $visibility)
     {
         $res = self::buildFromPIDs($cls, array($pid), $visibility);
         return array_pop($res);
@@ -49,7 +66,7 @@ abstract class ProfileField
      * @param $visibility An array of allowed visibility contexts
      * @return An array of $pid => ProfileField
      */
-    public static function buildFromPIDs($cls, array $pids, $visibility)
+    public static function buildFromPIDs($cls, array $pids, ProfileVisibility $visibility)
     {
         $it = new ProfileFieldIterator($cls, $pids, $visibility);
         $res = array();
@@ -59,7 +76,7 @@ abstract class ProfileField
         return $res;
     }
 
-    public static function getForPID($cls, $pid, $visibility)
+    public static function getForPID($cls, $pid, ProfileVisibility $visibility)
     {
         $it = new ProfileFieldIterator($cls, array($pid), $visibility);
         return $it->next();
@@ -73,7 +90,7 @@ class ProfileFieldIterator implements PlIterator
     private $data;
     private $cls;
 
-    public function __construct($cls, array $pids, $visibility)
+    public function __construct($cls, array $pids, ProfileVisibility $visibility)
     {
         $this->data = call_user_func(array($cls, 'fetchData'), $pids, $visibility);
         $this->cls = $cls;
@@ -119,13 +136,15 @@ class Phone
     public $display;
     public $comment = '';
 
-    const LINK_JOB     = 'job';
+    const LINK_JOB     = 'pro';
     const LINK_ADDRESS = 'address';
     const LINK_PROFILE = 'user';
     const LINK_COMPANY = 'hq';
     public $link_type;
     public $link_id;
 
+    public $id;
+
     /** Fields are :
      * $type, $search, $display, $link_type, $link_id, $comment, $pid, $id
      */
@@ -135,6 +154,67 @@ class Phone
             $this->$key = $val;
         }
     }
+
+    /** Returns the unique ID of a phone
+     * This ID will allow to link it to an address, a user or a job
+     * The format is address_addressId_phoneId (where phoneId is the id
+     * of the phone in the list of those associated with the address)
+     */
+    public function uid() {
+        return $this->link_type . '_' . $this->link_id . '_' . $this->id;
+    }
+
+    public function hasFlags($flags) {
+        return $this->hasType($flags) && $this->hasLink($flags);
+    }
+
+    /** Returns true if this phone's type matches the flags
+     */
+    public function hasType($flags) {
+        $flags = $flags & Profile::PHONE_TYPE_ANY;
+        return (
+            ($flags == Profile::PHONE_TYPE_ANY)
+            ||
+            (($flags & Profile::PHONE_TYPE_FAX) && $this->type == self::TYPE_FAX)
+            ||
+            (($flags & Profile::PHONE_TYPE_FIXED) && $this->type == self::TYPE_FIXED)
+            ||
+            (($flags & Profile::PHONE_TYPE_MOBILE) && $this->type == self::TYPE_MOBILE)
+        );
+    }
+
+    /** User accessible version of the type
+     */
+    public function displayType($short = false)
+    {
+        switch ($this->type) {
+          case Phone::TYPE_FIXED:
+            return $short ? 'Tél' : 'Fixe';
+          case Phone::TYPE_FAX:
+            return 'Fax';
+          case Phone::TYPE_MOBILE:
+            return $short ? 'Mob' : 'Mobile';
+          default:
+            return $this->type;
+        }
+    }
+
+    /** Returns true if this phone's link matches the flags
+     */
+    public function hasLink($flags) {
+        $flags = $flags & Profile::PHONE_LINK_ANY;
+        return (
+            ($flags == Profile::PHONE_LINK_ANY)
+            ||
+            (($flags & Profile::PHONE_LINK_COMPANY) && $this->link_type == self::LINK_COMPANY)
+            ||
+            (($flags & Profile::PHONE_LINK_JOB) && $this->link_type == self::LINK_JOB)
+            ||
+            (($flags & Profile::PHONE_LINK_ADDRESS) && $this->link_type == self::LINK_ADDRESS)
+            ||
+            (($flags & Profile::PHONE_LINK_PROFILE) && $this->link_type == self::LINK_PROFILE)
+        );
+    }
 }
 // }}}
 // {{{ class Company
@@ -179,15 +259,19 @@ class Job
     public $pid;
     public $id;
 
-    private $company = null;
-    private $phones = array();
-    private $address = null;
+    public $company = null;
+    public $phones = array();
+    public $address = null;
 
-    public $company_id;
+    public $jobid;
 
     public $description;
-    public $url;
-    public $email;
+    public $user_site;
+    public $user_email;
+
+    public $sector;
+    public $subsector;
+    public $subsubsector;
 
     /** Fields are:
      * pid, id, company_id, description, url, email
@@ -197,7 +281,12 @@ class Job
         foreach ($data as $key => $val) {
             $this->$key = $val;
         }
-        $this->setCompany(CompanyList::get($this->jobid));
+        $this->company = CompanyList::get($this->jobid);
+        if (is_null($this->company)) {
+            require_once 'validations.inc.php';
+            $entreprise = ProfileValidate::get_typed_requests($this->pid, 'entreprise');
+            $this->company = new Company(array('name' =>  $entreprise[$this->id]->name));
+        }
     }
 
     public function phones()
@@ -205,29 +294,24 @@ class Job
         return $this->phones;
     }
 
-    public function company()
+    public function address()
     {
-        return $this->company;
+        return $this->address;
     }
 
     public function addPhone(Phone &$phone)
     {
         if ($phone->link_type == Phone::LINK_JOB && $phone->link_id == $this->id && $phone->pid == $this->pid) {
-            $this->phones[] = $phone;
+            $this->phones[$phone->uid()] = $phone;
         }
     }
 
     public function setAddress(Address $address)
     {
-        if ($address->link_id == Address::LINK_JOB && $address->link_id == $this->id && $address->pid == $this->pid) {
+        if ($address->link_type == Address::LINK_JOB && $address->link_id == $this->id && $address->pid == $this->pid) {
             $this->address = $address;
         }
     }
-
-    public function setCompany(Company $company)
-    {
-        $this->company = $company;
-    }
 }
 // }}}
 // {{{ class Address
@@ -237,14 +321,23 @@ class Address
     const LINK_COMPANY = 'hq';
     const LINK_PROFILE = 'home';
 
-    public $link_id;
+    public $flags;
+    public $id; // The ID of the address among those associated with its link
+    public $link_id; // The ID of the object to which the address is linked (profile, job, company)
     public $link_type;
 
-    public $flags;
     public $text;
     public $postalCode;
+    public $latitude;
+    public $longitude;
+
+    public $locality;
+    public $subAdministrativeArea;
+    public $administrativeArea;
     public $country;
 
+    public $comment;
+
     private $phones = array();
 
     /** Fields are:
@@ -255,12 +348,23 @@ class Address
         foreach ($data as $key => $val) {
             $this->$key = $val;
         }
+        $this->flags = new PlFlagSet($this->flags);
+    }
+
+    public function uid() {
+        $uid = $this->link_type . '_';
+        if ($this->link_type != self::LINK_COMPANY) {
+            $uid .= $this->pid . '_';
+        }
+        $uid .= $this->link_id . '_' . $this->id;
     }
 
     public function addPhone(Phone &$phone)
     {
-        if ($phone->link_type == Phone::LINK_ADDRESS && $phone->link_id == $this->id && $phone->pid == $this->pid) {
-            $this->phones[] = $phone;
+        if (
+            $phone->link_type == Phone::LINK_ADDRESS && $phone->link_id == $this->id &&
+            ($this->link_type == self::LINK_COMPANY || $phone->pid == $this->pid) ) {
+            $this->phones[$phone->uid()] = $phone;
         }
     }
 
@@ -269,34 +373,43 @@ class Address
         return $this->phones;
     }
 
-    public function hasFlags($flags)
+    public function hasFlag($flag)
     {
-        return $flags & $this->flags;
+        if (!$this->flags instanceof PlFlagSet) {
+            $this->flags = new PlFlagSet($this->flags);
+        }
+        return $this->flags->hasFlag($flag);
     }
 }
 // }}}
 // {{{ class Education
 class Education
 {
-    public $eduid;
-    public $degreeid;
-    public $fieldid;
+    public $id;
+    public $pid;
 
     public $entry_year;
     public $grad_year;
     public $program;
     public $flags;
 
+    public $school;
+    public $school_short;
+    public $school_url;
+    public $country;
+
+    public $degree;
+    public $degree_short;
+    public $degree_level;
+
+    public $field;
+
     public function __construct(array $data)
     {
-        $this->eduid    = $data['eduid'];
-        $this->degreeid = $data['degreeid'];
-        $this->fieldid  = $data['fieldid'];
-
-        $this->entry_year = $data['entry_year'];
-        $this->grad_year  = $data['grad_year'];
-        $this->program    = $data['program'];
-        $this->flags      = new PlFlagSet($data['flags']);
+        foreach ($data as $key => $val) {
+            $this->$key = $val;
+        }
+        $this->flags      = new PlFlagSet($this->flags);
     }
 }
 // }}}
@@ -306,10 +419,9 @@ class ProfileEducation extends ProfileField
 {
     private $educations = array();
 
-    public function __construct(PlIterator $it)
+    public function __construct(PlInnerSubIterator $it)
     {
         $this->pid = $it->value();
-        $this->visibility = Profile::VISIBILITY_PUBLIC;
         while ($edu = $it->next()) {
             $this->educations[$edu['id']] = new Education($edu);
         }
@@ -330,6 +442,8 @@ class ProfileEducation extends ProfileField
                 (($flags & Profile::EDUCATION_FINISHED) && $edu->grad_year <= $year)
                 ||
                 (($flags & Profile::EDUCATION_CURRENT) && $edu->grad_year > $year)
+                ||
+                ($flags & Profile::EDUCATION_ALL)
             ) {
                 $educations[$id] = $edu;
                 ++$nb;
@@ -338,17 +452,25 @@ class ProfileEducation extends ProfileField
                 break;
             }
         }
-        return PlIteratorUtils::fromArray($educations);
+        return $educations;
     }
 
-    public static function fetchData(array $pids, $visibility)
+    public static function fetchData(array $pids, ProfileVisibility $visibility)
     {
-        $data = XDB::iterator('SELECT  id, pid, eduid, degreeid, fieldid,
-                                       entry_year, grad_year, program, flags
-                                 FROM  profile_education
-                                WHERE  pid IN {?}
+        $data = XDB::iterator('SELECT  pe.id, pe.pid,
+                                       pe.entry_year, pe.grad_year, pe.program, pe.flags,
+                                       pee.name AS school, pee.abbreviation AS school_short,
+                                       pee.url AS school_url, gc.countryFR AS country,
+                                       pede.degree, pede.abbreviation AS degree_short, pede.level AS degree_level,
+                                       pefe.field
+                                 FROM  profile_education AS pe
+                            LEFT JOIN  profile_education_enum AS pee ON (pee.id = pe.eduid)
+                            LEFT JOIN  geoloc_countries AS gc ON (gc.iso_3166_1_a2 = pee.country)
+                            LEFT JOIN  profile_education_degree_enum AS pede ON (pede.id = pe.degreeid)
+                            LEFT JOIN  profile_education_field_enum AS pefe ON (pefe.id = pe.fieldid)
+                                WHERE  pe.pid IN {?}
                              ORDER BY  ' . XDB::formatCustomOrder('pid', $pids) . ',
-                                       NOT FIND_IN_SET(\'primary\', flags), entry_year, id',
+                                       NOT FIND_IN_SET(\'primary\', pe.flags), pe.entry_year, pe.id',
                                 $pids);
 
         return PlIteratorUtils::subIterator($data, PlIteratorUtils::arrayValueCallback('pid'));
@@ -360,23 +482,24 @@ class ProfileMedals extends ProfileField
 {
     public $medals = array();
 
-    public function __construct(PlIterator $it)
+    public function __construct(PlInnerSubIterator $it)
     {
+        $this->pid = $it->value();
         while ($medal = $it->next()) {
-            $this->medals[$medal['mid']] = $medal['gid'];
+            $this->medals[$medal['mid']] = $medal;
         }
     }
 
-    public static function fetchData(array $pids, $visibility)
+    public static function fetchData(array $pids, ProfileVisibility $visibility)
     {
-        $data = XDB::iterator('SELECT  pm.pid, pm.mid, pm.gid
+        $data = XDB::iterator('SELECT  pm.pid, pm.mid, pm.gid, pme.text, pme.img, pmge.text AS grade
                                  FROM  profile_medals AS pm
                             LEFT JOIN  profiles AS p ON (pm.pid = p.pid)
+                            LEFT JOIN  profile_medal_enum AS pme ON (pme.id = pm.mid)
+                            LEFT JOIN  profile_medal_grade_enum AS pmge ON (pmge.mid = pm.mid AND pmge.gid = pm.gid)
                                 WHERE  pm.pid IN {?} AND p.medals_pub IN {?}
                              ORDER BY  ' . XDB::formatCustomOrder('pm.pid', $pids),
-                                XDB::formatArray($pids),
-                                XDB::formatArray($visibility)
-                            );
+                                $pids, $visibility->levels());
 
         return PlIteratorUtils::subIterator($data, PlIteratorUtils::arrayValueCallback('pid'));
     }
@@ -387,21 +510,24 @@ class ProfileNetworking extends ProfileField
 {
     private $networks = array();
 
-    public function __construct(PlIterator $it)
+    public function __construct(PlInnerSubIterator $it)
     {
+        $this->pid = $it->value();
         while ($network = $it->next()) {
-            $this->networks[$network['nwid']] = $network['address'];
+            $network['network_type'] = new PlFlagSet($network['network_type']);
+            $this->networks[$network['id']] = $network;
         }
     }
 
-    public static function fetchData(array $pids, $visibility)
+    public static function fetchData(array $pids, ProfileVisibility $visibility)
     {
-        $data = XDB::iterator('SELECT  pid, nwid, address, network_type
-                                 FROM  profile_networking
+        $data = XDB::iterator('SELECT  pid, id, address, pne.nwid, pne.network_type, pne.link, pne.name
+                                 FROM  profile_networking AS pn
+                            LEFT JOIN  profile_networking_enum AS pne USING(nwid)
                                 WHERE  pid IN {?} AND pub IN {?}
                              ORDER BY  ' . XDB::formatCustomOrder('pid', $pids) . ',
-                                       network_type, nwid',
-                               $pids, $visibility);
+                                       pn.nwid, id',
+                               $pids, $visibility->levels());
 
         return PlIteratorUtils::subIterator($data, PlIteratorUtils::arrayValueCallback('pid'));
     }
@@ -411,80 +537,115 @@ class ProfileNetworking extends ProfileField
         $nws = array();
         $nb = 0;
         foreach ($this->networks as $id => $nw) {
-            // XXX hardcoded reference to web site index
-            if (
-                (($flags & self::NETWORKING_WEB) && $nw['network_type'] == 0)
-                ||
-                (! ($flags & self::NETWORKING_WEB))
-            ) {
+            if (($flags & Profile::NETWORKING_WEB) && $nw['network_type']->hasFlag('web') ||
+                ($flags & Profile::NETWORKING_IM) && $nw['network_type']->hasFlag('im') ||
+                ($flags & Profile::NETWORKING_SOCIAL) && $nw['network_type']->hasFlag('social') ||
+                ($flags == Profile::NETWORKING_ALL)) {
                 $nws[$id] = $nw;
                 ++$nb;
-            }
-            if ($nb >= $limit) {
-                break;
+                if (isset($limit) && $nb >= $limit) {
+                    break;
+                }
             }
         }
-        return PlIteratorUtils::fromArray($nws);
+        return $nws;
     }
 }
 // }}}
-// {{{ class ProfilePhoto                             [ Field ]
-class ProfilePhoto extends ProfileField
+// {{{ class ProfileCorps                             [ Field ]
+class ProfileCorps extends ProfileField
 {
-    public $pic;
+    public $original;
+    public $current;
+
+    public $original_name;
+    public $original_abbrev;
+    public $original_still_exists;
+
+    public $current_name;
+    public $current_abbrev;
+    public $current_still_exists;
+    public $current_rank;
+    public $current_rank_abbrev;
 
     public function __construct(array $data)
     {
-        if ($data == null || count($data) == 0) {
-            $this->pic = null;
-        } else {
-            $this->pid = $data['pid'];
-            $this->pic = PlImage::fromDATA($data['attach'],
-                                           $data['attachmime'],
-                                           $data['x'],
-                                           $data['y']);
+        foreach ($data as $key => $val) {
+            $this->$key = $val;
         }
     }
 
-    public static function fetchData(array $pids, $visibility)
+    public static function fetchData(array $pids, ProfileVisibility $visibility)
     {
-        $data = XDB::iterator('SELECT  *
-                                 FROM  profile_photos
-                                WHERE  pid IN {?} AND attachmime IN (\'jpeg\', \'png\') AND pub IN {?}
+        $data = XDB::iterator('SELECT  pc.pid, pc.original_corpsid AS original, pc.current_corpsid AS current,
+                                       pceo.name AS original_name, pceo.abbreviation AS original_abbrev,
+                                       pceo.still_exists AS original_still_exists,
+                                       pcec.name AS current_name, pcec.abbreviation AS current_abbrev,
+                                       pcec.still_exists AS current_still_exists,
+                                       pcrec.name AS current_rank, pcrec.abbreviation AS current_rank_abbrev,
+                                       rankid
+                                 FROM  profile_corps AS pc
+                            LEFT JOIN  profile_corps_enum AS pceo ON (pceo.id = pc.original_corpsid)
+                            LEFT JOIN  profile_corps_enum AS pcec ON (pcec.id = pc.current_corpsid)
+                            LEFT JOIN  profile_corps_rank_enum AS pcrec ON (pcrec.id = pc.rankid)
+                                WHERE  pc.pid IN {?} AND pc.corps_pub IN {?} AND pceo.id != 1
                              ORDER BY  ' . XDB::formatCustomOrder('pid', $pids),
-                               $pids, $visibility);
+                                $pids, $visibility->levels());
 
         return $data;
     }
 }
 // }}}
-// {{{ class ProfileCorps                             [ Field ]
-class ProfileCorps extends ProfileField
+// {{{ class ProfileMentoringSectors                  [ Field ]
+class ProfileMentoringSectors extends ProfileField
 {
-    public $original;
-    public $current;
-    public $rank;
+    public $sectors = array();
 
-    public function __construct(array $data)
+    public function __construct(PlInnerSubIterator $it)
     {
-        $this->original = $data['original_corpsid'];
-        $this->current  = $data['current_corpsid'];
-        $this->rank     = $data['rankid'];
-        $this->visibility = $data['corps_pub'];
+        $this->pid = $it->value();
+        while ($sector = $it->next()) {
+            $this->sectors[] = $sector;
+        }
     }
 
-    public static function fetchData(array $pids, $visibility)
+    public static function fetchData(array $pids, ProfileVisibility $visibility)
     {
-        $data = XDB::iterator('SELECT  pid, original_corpsid, current_corpsid,
-                                       rankid
-                                 FROM  profile_corps
-                                WHERE  pid IN {?} AND corps_pub IN {?}
-                             ORDER BY  ' . XDB::formatCustomOrder('pid', $pids),
-                                XDB::formatArray($pids),
-                                XDB::formatArray($visibility)
-                            );
+        $data = XDB::iterator('SELECT  pms.pid, pjse.name AS sector, pjsse.name AS subsector
+                                 FROM  profile_mentor_sector AS pms
+                            LEFT JOIN  profile_job_sector_enum AS pjse ON (pjse.id = pms.sectorid)
+                            LEFT JOIN  profile_job_subsector_enum AS pjsse ON (pjsse.id = pms.subsectorid)
+                                WHERE  pms.pid IN {?}
+                             ORDER BY  ' . XDB::formatCustomOrder('pms.pid', $pids),
+                                $pids);
 
-        return $data;
+        return PlIteratorUtils::subIterator($data, PlIteratorUtils::arrayValueCallback('pid'));
+    }
+}
+// }}}
+// {{{ class ProfileMentoringCountries                [ Field ]
+class ProfileMentoringCountries extends ProfileField
+{
+    public $countries = array();
+
+    public function __construct(PlInnerSubIterator $it)
+    {
+        $this->pid = $it->value();
+        while ($country = $it->next()) {
+            $this->countries[$country['id']] = $country['name'];
+        }
+    }
+
+    public static function fetchData(array $pids, ProfileVisibility $visibility)
+    {
+        $data = XDB::iterator('SELECT  pmc.pid, pmc.country AS id, gc.countryFR AS name
+                                 FROM  profile_mentor_country AS pmc
+                            LEFT JOIN  geoloc_countries AS gc ON (gc.iso_3166_1_a2 = pmc.country)
+                                WHERE  pmc.pid IN {?}
+                             ORDER BY  ' . XDB::formatCustomOrder('pmc.pid', $pids),
+                                $pids);
+
+        return PlIteratorUtils::subIterator($data, PlIteratorUtils::arrayValueCallback('pid'));
     }
 }
 // }}}
@@ -495,6 +656,64 @@ class ProfileCorps extends ProfileField
  * 3) attach addresses to jobs and profiles
  */
 
+// {{{ Database schema (profile_address, profile_phones, profile_jobs)
+/** The database for this is very unclear, so here is a little schema :
+ * profile_job describes a Job, links to:
+ * - a Profile, through `pid`
+ * - a Company, through `jobid`
+ * The `id` field is the id of this job in the list of the jobs of its profile
+ *
+ * profile_addresses describes an Address, which
+ * related to either a Profile, a Job or a Company:
+ * - for a Profile:
+ *   - `type` is set to 'home'
+ *   - `pid` is set to the related profile pid
+ *   - `id` is the id of the address in the list of those related to that profile
+ *   - `jobid` is empty
+ *
+ * - for a Company:
+ *   - `type` is set to 'hq'
+ *   - `pid` is set to 0
+ *   - `jobid` is set to the id of the company
+ *   - `id` is set to 0 (only one address per Company)
+ *
+ * - for a Job:
+ *   - `type` is set to 'job'
+ *   - `pid` is set to the pid of the Profile of the related Job
+ *   - `jobid` is set to the Company of the job (this information is redundant
+ *              with that of the row of profile_job for the related job)
+ *   - `id` is the id of the job to which we refer (i.e `profile_job.id`)
+ *
+ * profile_phone describes a Phone, which can be related to an Address,
+ * a Job, a Profile or a Company:
+ * - for a Profile:
+ *   - `link_type` is set to 'user'
+ *   - `link_id` is set to 0
+ *   - `pid` is set to the id of the related Profile
+ *
+ * - for a Company:
+ *   - `link_type` is set to 'hq'
+ *   - `link_id` is set to the id of the related Company
+ *   - `pid` is set to 0
+ *
+ * - for an Address (this is only possible for a *personal* address)
+ *   - `link_type` is set to 'address'
+ *   - `link_id` is set to the related Address `id`
+ *   - `pid` is set to the related Address `pid`
+ *
+ * - for a Job:
+ *   - `link_type` is set to 'pro'
+ *   - `link_id` is set to the related Job `id` (not `jobid`)
+ *   - `pid` is set to the related Job `pid`
+ *
+ *
+ * The possible relations are as follow:
+ * An Address can be linked to a Company, a Profile, a Job
+ * A Job is linked to a Company and a Profile
+ * A Phone can be linked to a Company, a Profile, a Job, or a Profile-related Address
+ */
+// }}}
+
 // {{{ class ProfileAddresses                         [ Field ]
 class ProfileAddresses extends ProfileField
 {
@@ -516,7 +735,15 @@ class ProfileAddresses extends ProfileField
         $res = array();
         $nb = 0;
         foreach ($this->addresses as $addr) {
-            if ($addr->hasFlags($flags)) {
+            if (
+                (($flags & Profile::ADDRESS_MAIN) && $addr->hasFlag('current'))
+                ||
+                (($flags & Profile::ADDRESS_POSTAL) && $addr->hasFlag('mail'))
+                ||
+                (($flags & Profile::ADDRESS_PERSO) && $addr->link_type == Address::LINK_PROFILE)
+                ||
+                (($flags & Profile::ADDRESS_PRO) && $addr->link_type == Address::LINK_JOB)
+            ) {
                 $res[] = $addr;
                 $nb++;
             }
@@ -524,25 +751,32 @@ class ProfileAddresses extends ProfileField
                 break;
             }
         }
-        return PlIteratorUtils::fromArray($res);
+        return $res;
     }
 
-    public static function fetchData(array $pids, $visibility)
+    public static function fetchData(array $pids, ProfileVisibility $visibility)
     {
-        $data = XDB::iterator('SELECT  pid, text, postalCode, type, latitude, longitude,
-                                       flags, type
-                                 FROM  profile_addresses
-                                WHERE  pid in {?} AND pub IN {?}
+        $data = XDB::iterator('SELECT  pa.id, pa.pid, pa.flags, pa.type AS link_type,
+                                       IF(pa.type = \'home\', pid, IF(pa.type = \'job\', pa.id, jobid)) AS link_id,
+                                       pa.text, pa.postalCode, pa.latitude, pa.longitude, pa.comment,
+                                       gl.name AS locality, gas.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_administrativeareas AS gas ON (gas.id = pa.subAdministrativeAreaId)
+                            LEFT JOIN  geoloc_countries AS gc ON (gc.iso_3166_1_a2 = pa.countryId)
+                                WHERE  pa.pid in {?} AND pa.pub IN {?}
                              ORDER BY  ' . XDB::formatCustomOrder('pid', $pids),
-                               $pids, $visibility);
+                               $pids, $visibility->levels());
 
         return PlIteratorUtils::subIterator($data, PlIteratorUtils::arrayValueCallback('pid'));
     }
 
     public function addPhones(ProfilePhones $phones)
     {
-        $p = $phones->get(0);
-        while ($phone = $p->next()) {
+        $p = $phones->get(Profile::PHONE_LINK_ADDRESS | Profile::PHONE_TYPE_ANY);
+        foreach ($p as $phone) {
             if ($phone->link_type == Phone::LINK_ADDRESS && array_key_exists($phone->link_id, $this->addresses)) {
                 $this->addresses[$phone->link_id]->addPhone($phone);
             }
@@ -555,10 +789,11 @@ class ProfilePhones extends ProfileField
 {
     private $phones = array();
 
-    public function __construct(PlIterator $phones)
+    public function __construct(PlInnerSubIterator $it)
     {
+        $this->pid = $it->value();
         while ($phone = $it->next()) {
-            $this->phones[] = Phone::buildFromData($phone);
+            $this->phones[] = new Phone($phone);
         }
     }
 
@@ -567,24 +802,24 @@ class ProfilePhones extends ProfileField
         $phones = array();
         $nb = 0;
         foreach ($this->phones as $id => $phone) {
-            $phones[$id] = $phone;
-            ++$nb;
-            if ($limit != null && $nb == $limit) {
-                break;
+            if ($phone->hasFlags($flags)) {
+                $phones[$id] = $phone;
+                ++$nb;
+                if ($limit != null && $nb == $limit) {
+                    break;
+                }
             }
         }
-        return PlIteratorUtils::fromArray($phones);
+        return $phones;
     }
 
-    public static function fetchData(array $pids, $visibility)
+    public static function fetchData(array $pids, ProfileVisibility $visibility)
     {
-        $data = XDB::iterator('SELECT  type, search, display, link_type, comment
+        $data = XDB::iterator('SELECT  tel_type AS type, search_tel AS search, display_tel AS display, link_type, comment, pid, link_id, tel_id AS id
                                  FROM  profile_phones
                                 WHERE  pid IN {?} AND pub IN {?}
                              ORDER BY  ' . XDB::formatCustomOrder('pid', $pids),
-                                 XDB::formatArray($pids),
-                                 XDB::formatArray($visibility)
-                             );
+                                 $pids, $visibility->levels());
         return PlIteratorUtils::subIterator($data, PlIteratorUtils::arrayValueCallback('pid'));
     }
 }
@@ -594,24 +829,29 @@ class ProfileJobs extends ProfileField
 {
     private $jobs = array();
 
-    public function __construct(PlIterator $jobs)
+    public function __construct(PlInnerSubIterator $jobs)
     {
+        $this->pid = $jobs->value();
         while ($job = $jobs->next()) {
             $this->jobs[$job['id']] = new Job($job);
         }
     }
 
-    public static function fetchData(array $pids, $visibility)
+    public static function fetchData(array $pids, ProfileVisibility $visibility)
     {
         CompanyList::preload($pids);
-        $data = XDB::iterator('SELECT  id, pid, description, url,
-                                       jobid, sectorid, subsectorid, subsubsectorid,
-                                       IF(email_pub IN {?}, email, NULL) AS email
-                                 FROM  profile_job
-                                WHERE  pid IN {?} AND pub IN {?}
+        $data = XDB::iterator('SELECT  pj.id, pj.pid, pj.description, pj.url as user_site,
+                                       IF(pj.email_pub IN {?}, pj.email, NULL) AS user_email,
+                                       pj.jobid, pjse.name AS sector, pjsse.name AS subsector,
+                                       pjssse.name AS subsubsector
+                                 FROM  profile_job AS pj
+                            LEFT JOIN  profile_job_sector_enum AS pjse ON (pjse.id = pj.sectorid)
+                            LEFT JOIN  profile_job_subsector_enum AS pjsse ON (pjsse.id = pj.subsectorid)
+                            LEFT JOIN  profile_job_subsubsector_enum AS pjssse ON (pjssse.id = pj.subsubsectorid)
+                                WHERE  pj.pid IN {?} AND pj.pub IN {?}
                              ORDER BY  ' . XDB::formatCustomOrder('pid', $pids) . ',
-                                       id',
-                                 $visibility, $pids, $visibility);
+                                       pj.id',
+                                 $visibility->levels(), $pids, $visibility->levels());
         return PlIteratorUtils::subIterator($data, PlIteratorUtils::arrayValueCallback('pid'));
     }
 
@@ -626,34 +866,33 @@ class ProfileJobs extends ProfileField
                 break;
             }
         }
-        return PlIteratorUtils::fromArray($jobs);
+        return $jobs;
     }
 
     public function addPhones(ProfilePhones $phones)
     {
-        $p = $phones->get(0);
-        while ($phone = $p->next()) {
+        $p = $phones->get(Profile::PHONE_LINK_JOB | Profile::PHONE_TYPE_ANY);
+        foreach ($p as $phone) {
             if ($phone->link_type == Phone::LINK_JOB && array_key_exists($phone->link_id, $this->jobs)) {
-                $this->jobs[$phone->link_id]->addPhones($phone);
+                $this->jobs[$phone->link_id]->addPhone($phone);
             }
         }
     }
 
-    public static function addAddresses(ProfileAddresses $addresses)
+    public function addAddresses(ProfileAddresses $addresses)
     {
         $a = $addresses->get(Profile::ADDRESS_PRO);
-        while ($address = $a->next()) {
+        foreach ($a as $address) {
             if ($address->link_type == Address::LINK_JOB && array_key_exists($address->link_id, $this->jobs)) {
                 $this->jobs[$address->link_id]->setAddress($address);
             }
         }
     }
 
-    public static function addCompanies(array $companies)
+    public function addCompanies(array $companies)
     {
-        foreach ($this->jobs as $job)
-        {
-            $job->setCompany($companies[$job->company_id]);
+        foreach ($this->jobs as $job) {
+            $this->company = $companies[$job->jobid];
         }
     }
 }
@@ -686,14 +925,29 @@ class CompanyList
                           LEFT JOIN  profile_addresses AS pa ON (pje.id = pa.jobid AND pa.type = \'hq\')
                                   ' . $join . '
                                   ' . $where);
+        $newcompanies = array();
         while ($row = $it->next()) {
             $cp = new Company($row);
             $addr = new Address($row);
             $cp->setAddress($addr);
+            if (!array_key_exists($row['id'], self::$companies)) {
+                $newcompanies[] = $row['id'];
+            }
             self::$companies[$row['id']] = $cp;
         }
 
-        // TODO: add phones to addresses
+        // Add phones to hq
+        if (count($newcompanies)) {
+            $it = XDB::iterator('SELECT  search_tel AS search, display_tel AS display, comment, link_id, tel_type AS type, link_type, tel_id AS id
+                                   FROM  profile_phones
+                                  WHERE  link_id IN {?} AND link_type = \'hq\'',
+                                    $newcompanies);
+            while ($row = $it->next()) {
+                $p = new Phone($row);
+                self::$companies[$row['link_id']]->setPhone($p);
+            }
+        }
+
         if (count($pids) == 0) {
             self::$fullload = true;
         }