Append selector instead of overwritting previous ones in Address::deleteAddresses
[platal.git] / classes / address.php
index bca9e5f..e325d1e 100644 (file)
@@ -1,6 +1,6 @@
 <?php
 /***************************************************************************
- *  Copyright (C) 2003-2011 Polytechnique.org                              *
+ *  Copyright (C) 2003-2014 Polytechnique.org                              *
  *  http://opensource.polytechnique.org/                                   *
  *                                                                         *
  *  This program is free software; you can redistribute it and/or modify   *
@@ -298,6 +298,7 @@ class Address
     // Geocoding fields.
     public $text = '';
     public $postalText = '';
+    public $postal_code_fr = null;
     public $types = '';
     public $formatted_address = '';
     public $components = array();
@@ -355,7 +356,7 @@ class Address
                                                                                array('', "\n"), $this->text)), 'CEDEX')) !== false);
             }
         }
-        $this->request = !is_null(AddressReq::get_request($this->pid, $this->jobid, $this->groupid, $this->type, $this->text));
+        $this->request = ($this->request || !is_null(AddressReq::get_request($this->pid, $this->jobid, $this->groupid, $this->type, $this->id)));
     }
 
     public function setId($id)
@@ -423,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:
@@ -492,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) {
@@ -499,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 = '';
@@ -536,6 +539,7 @@ class Address
             $arrayText[$lineNumber] = trim($formattedLine);
         }
 
+        $this->postal_code_fr = $postal_code;
         return implode("\n", $arrayText);
     }
 
@@ -575,7 +579,7 @@ class Address
     public function format()
     {
         $this->text = trim($this->text);
-        $this->phones = Phone::formatFormArray($this->phones, $this->error, new ProfileVisibility($this->pub));
+        $this->phones = Phone::formatFormArray($this->phones, $this->error, $this->pub);
         if ($this->removed == 1) {
             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.");
@@ -589,13 +593,17 @@ class Address
         if ($this->changed == 1) {
             $gmapsGeocoder = new GMapsGeocoder();
             $gmapsGeocoder->getGeocodedAddress($this);
-        }
 
-        $componants = array();
-        foreach ($this->components as $component) {
-            $componants[] = Geocoder::getComponentId($component);
+            $componants = array();
+            foreach ($this->components as $component) {
+                $componants[] = Geocoder::getComponentId($component);
+            }
+            $this->componentsIds = implode(',', $componants);
+        }
+        if ($this->componentsIds == '') {
+            $this->latitude = null;
+            $this->longitude = null;
         }
-        $this->componentsIds = implode(',', $componants);
 
         return true;
     }
@@ -621,14 +629,16 @@ class Address
             'request'             => $this->request
         );
 
-        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);
         }
@@ -640,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) {
@@ -681,68 +691,117 @@ class Address
         return (!$this->text || $this->text == '');
     }
 
-    public function save()
+    public function save($notify_ungeocoded = true)
     {
         if (!$this->isEmpty()) {
             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)
+                                                                 geocoding_date, geocoding_calls, postal_code_fr)
                                       VALUES  ({?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?},
-                                               {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, NOW(), {?})',
+                                               {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, 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->southwest_latitude, $this->southwest_longitude, $this->northeast_latitude, $this->northeast_longitude, $this->geocoding_calls, $this->postal_code_fr);
 
+            // In an ideal world there would not be any components to clean up before insertion.
+            // In real world, it happens that some addresses are badly removed and this query removes the leaked trash.
+            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);
                 }
+            } 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);
+            }
         }
     }
 
-    public function updateGeocoding($text)
+    /**
+     * 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)
     {
-        $id = null;
-        $texts = XDB::fetchAllAssoc('id', 'SELECT  id, text
-                                   FROM  profile_addresses
-                                  WHERE  pid = {?} AND jobid = {?} AND groupid = {?} AND type = {?}',
-                                $this->pid, $this->jobid, $this->groupid, $this->type);
-        $text = preg_replace('/\s+/', ' ', $text);
-        foreach ($texts as $key => $value) {
-            if (strcmp($text, preg_replace('/\s+/', ' ', $value)) == 0) {
-                $id = $key;
-                break;
-            }
+        if (!$fake) {
+            XDB::execute("UPDATE  profile_addresses
+                             SET  flags = REPLACE(flags, 'dn_best_mail', '')
+                           WHERE  pid = {?}",
+                         $pid);
         }
-        if (!is_null($id)) {
-            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 = {?}, geocoding_calls = NOW()
-                           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->pid, $this->jobid, $this->groupid, $this->type, $id, $this->geocoding_calls);
 
-            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, $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, $id, $component_id);
-                }
+        /* 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()
+    {
+        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);
             }
         }
     }
@@ -763,13 +822,17 @@ class Address
     {
         $where = '';
         if (!is_null($pid)) {
-            $where = XDB::format(' AND pid = {?}', $pid);
+            $where .= XDB::format(' AND pid = {?}', $pid);
         }
         if (!is_null($jobid)) {
-            $where = XDB::format(' AND jobid = {?}', $jobid);
+            $where .= XDB::format(' AND jobid = {?}', $jobid);
         }
         if (!is_null($groupid)) {
-            $where = XDB::format(' AND groupid = {?}', $groupid);
+            $where .= XDB::format(' AND groupid = {?}', $groupid);
+        }
+        // Prevent buggy callers from accidentally dropping profile_addresses
+        if (!$where) {
+            throw new Exception("Unable to delete all addresses of the given type, the request was too generic");
         }
         XDB::execute('DELETE FROM  profile_addresses
                             WHERE  type = {?}' . $where . (($deletePrivate) ? '' : ' AND pub IN (\'public\', \'ax\')'),
@@ -825,7 +888,7 @@ class Address
     // addresses before secondary addresses.
     static private function compare(array $a, array $b)
     {
-        $value = ProfileVisibility::comparePublicity($a, $b);
+        $value = Visibility::comparePublicity($a, $b);
         if ($value == 0) {
             if ($a['secondary'] != $b['secondary']) {
                 $value = $a['secondary'] ? 1 : -1;
@@ -877,26 +940,30 @@ class Address
     }
 
     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);
         }
@@ -906,35 +973,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);
+        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,
-                        pace1.long_name AS postalCode, pace2.long_name AS locality, pace3.long_name AS administrativeArea, pace4.long_name AS country
+                        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))
-             LEFT JOIN  profile_addresses_components_enum AS pace2 ON (FIND_IN_SET(\'locality\', pace2.types))
-             LEFT JOIN  profile_addresses_components_enum AS pace3 ON (FIND_IN_SET(\'administrative_area_level_1\', pace3.types))
-             LEFT JOIN  profile_addresses_components_enum AS pace4 ON (FIND_IN_SET(\'country\', pace4.types))
-             LEFT JOIN  profile_addresses_components      AS pac1  ON (pa.pid = pac1.pid AND pa.jobid = pac1.jobid AND pa.groupid = pac1.groupid
-                                                                       AND pa.id = pac1.id AND pa.type = pac1.type AND pace1.id = pac1.component_id)
-             LEFT JOIN  profile_addresses_components      AS pac2  ON (pa.pid = pac2.pid AND pa.jobid = pac2.jobid AND pa.groupid = pac2.groupid
-                                                                       AND pa.id = pac2.id AND pa.type = pac2.type AND pace2.id = pac2.component_id)
-             LEFT JOIN  profile_addresses_components      AS pac3  ON (pa.pid = pac3.pid AND pa.jobid = pac3.jobid AND pa.groupid = pac3.groupid
-                                                                       AND pa.id = pac3.id AND pa.type = pac3.type AND pace3.id = pac3.component_id)
-             LEFT JOIN  profile_addresses_components      AS pac4  ON (pa.pid = pac4.pid AND pa.jobid = pac4.jobid AND pa.groupid = pac4.groupid
-                                                                       AND pa.id = pac4.id AND pa.type = pac4.type AND pace4.id = pac4.component_id)
-
-                 ' . ((count($where) > 0) ? 'WHERE  ' . implode(' AND ', $where) : '') . '
+             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()
@@ -947,7 +1010,7 @@ 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();
         }
@@ -975,5 +1038,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:
 ?>