Editing the name of a profile update the name of the associated account
[platal.git] / modules / profile / general.inc.php
index 5e70adc..13106c1 100644 (file)
  *  59 Temple Place, Suite 330, Boston, MA  02111-1307  USA                *
  ***************************************************************************/
 
-class ProfileSearchNames implements ProfileSetting
+require_once 'name.func.inc.php';
+
+class ProfileSettingSearchNames implements ProfileSetting
 {
     private $private_name_end;
     private $search_names;
+    private $name_types;
+
+    public function __construct() {
+            $this->name_types = DirEnum::getOptions(DirEnum::NAMES);
+    }
 
     private function matchWord($old, $new, $newLen)
     {
@@ -33,8 +40,7 @@ class ProfileSearchNames implements ProfileSetting
 
     private function prepareField($value)
     {
-        $value = mb_strtoupper($value);
-        return preg_replace('/[^A-Z]/', ' ', $value);
+        return name_to_basename($value);
     }
 
     private function prepare(ProfilePage &$page, $field, $value, $init, &$success)
@@ -47,12 +53,33 @@ class ProfileSearchNames implements ProfileSetting
                    || ($field == 'lastname' && $new == 'DE ' . $ini);
         if (!$success) {
             $field = strtolower($field);
-            Platal::page()->trigError("Le " . $field . " que tu as choisi (" . $value .
-                                      ") est trop loin de ton " . $field . " initial (" . $init . ").");
+            Platal::page()->trigError("Le " . $this->name_types[$field] . " que tu as choisi (" . $value .
+                                      ") est trop loin de ton " . $this->name_types[$field] . " initial (" . $init . ").");
         }
         return $success ? $value : $init;
     }
 
+    /* Removes duplicated entries for the fields that do not allow them. */
+    private function clean($value)
+    {
+        $single_types = XDB::fetchAllAssoc('id',
+                                           'SELECT  id, 0
+                                              FROM  profile_name_enum
+                                             WHERE  NOT FIND_IN_SET(\'allow_duplicates\', flags)');
+
+        foreach ($value as $key => $item) {
+            if (isset($single_types[$item['typeid']])) {
+                if ($single_types[$item['typeid']] === true) {
+                    unset($value[$key]);
+                } else {
+                    $single_types[$item['typeid']] = true;
+                }
+            }
+        }
+
+        return $value;
+    }
+
     public function value(ProfilePage &$page, $field, $value, &$success)
     {
         $success     = true;
@@ -101,14 +128,16 @@ class ProfileSearchNames implements ProfileSetting
                     $value[] = $sn;
                 } while ($sn = $sn_all->next());
             }
+            $value = $this->clean($value);
         } else {
             require_once 'name.func.inc.php';
 
+            $value = $this->clean($value);
             $res = XDB::query("SELECT  s.particle, s.name
                                  FROM  profile_name      AS s
                            INNER JOIN  profile_name_enum AS e ON (e.id = s.typeid)
-                                WHERE  s.pid = {?} AND e.type LIKE '%ini'
-                             ORDER BY  e.type = 'firstname_ini'",
+                                WHERE  s.pid = {?} AND (e.type = 'lastname' OR e.type = 'firstname')
+                             ORDER BY  e.type = 'firstname'",
                              $page->pid());
             $res = $res->fetchAllAssoc();
             $initial = array();
@@ -125,11 +154,18 @@ class ProfileSearchNames implements ProfileSetting
                 }
                 if ($sn['pub']) {
                     if (isset($sn['particle']) && ($sn['particle'] != '')) {
+                        // particle is before first blank
                         list($particle, $name) = explode(' ', $sn['name'], 2);
                         $particle = trim($particle) . ' ';
                         if (!$name) {
+                            // particle is before first quote
                             list($particle, $name) = explode('\'', $sn['name'], 2);
                             $particle = trim($particle);
+                            if (!$name) {
+                                // actually there is no particle
+                                $particle = '';
+                                $name = $sn['name'];
+                            }
                         }
                     } else {
                         $particle = '';
@@ -172,29 +208,30 @@ class ProfileSearchNames implements ProfileSetting
     public function save(ProfilePage &$page, $field, $value)
     {
         require_once 'name.func.inc.php';
-        $sn_old = build_sn_pub();
+        $sn_old = build_sn_pub($page->pid());
         XDB::execute("DELETE FROM  s
                             USING  profile_name      AS s
                        INNER JOIN  profile_name_enum AS e ON (s.typeid = e.id)
                             WHERE  s.pid = {?} AND NOT FIND_IN_SET('not_displayed', e.flags)",
                      $page->pid());
-        $has_new = set_alias_names($this->search_names, $sn_old);
+        $has_new = set_alias_names($this->search_names, $sn_old, $page->pid(), $page->owner->id());
 
         // Only requires validation if modification in public names
         if ($has_new) {
             $new_names = new NamesReq(S::user(), $this->search_names, $this->private_name_end);
             $new_names->submit();
-            Platal::page()->trigWarning("La demande de modification de tes noms a bien été prise en compte." .
-                                        " Tu recevras un email dès que ces changements auront été effectués.");
+            Platal::page()->trigWarning('La demande de modification de tes noms a bien été prise en compte.' .
+                                        ' Tu recevras un email dès que ces changements auront été effectués.');
         } else {
             $display_names = array();
-            build_display_names($display_names, $this->search_names, $this->private_name_end);
-            set_profile_display($display_names);
+            build_display_names($display_names, $this->search_names,
+                                $page->profile->isFemale(), $this->private_name_end);
+            set_profile_display($display_names, $page->pid());
         }
     }
 }
 
-class ProfileEdu implements ProfileSetting
+class ProfileSettingEdu implements ProfileSetting
 {
     public function __construct() {
     }
@@ -215,7 +252,7 @@ class ProfileEdu implements ProfileSetting
             $value = array();
             $value = XDB::fetchAllAssoc("SELECT  eduid, degreeid, fieldid, grad_year, program
                                            FROM  profile_education
-                                          WHERE  uid = {?} AND !FIND_IN_SET('primary', flags)
+                                          WHERE  pid = {?} AND !FIND_IN_SET('primary', flags)
                                        ORDER BY  id",
                                         $page->pid());
         } else {
@@ -232,7 +269,7 @@ class ProfileEdu implements ProfileSetting
                 }
                 $i++;
             }
-            usort($value, array("ProfileEdu", "sortByGradYear"));
+            usort($value, array("ProfileSettingEdu", "sortByGradYear"));
         }
         return $value;
     }
@@ -240,12 +277,12 @@ class ProfileEdu implements ProfileSetting
     public function save(ProfilePage &$page, $field, $value)
     {
         XDB::execute("DELETE FROM  profile_education
-                            WHERE  uid = {?} AND !FIND_IN_SET('primary', flags)",
+                            WHERE  pid = {?} AND !FIND_IN_SET('primary', flags)",
                      $page->pid());
         foreach ($value as $eduid=>&$edu) {
             if ($edu['eduid'] != '') {
                 XDB::execute("INSERT INTO  profile_education
-                                      SET  id = {?}, uid = {?}, eduid = {?}, degreeid = {?},
+                                      SET  id = {?}, pid = {?}, eduid = {?}, degreeid = {?},
                                            fieldid = {?}, grad_year = {?}, program = {?}",
                              $eduid, $page->pid(), $edu['eduid'], $edu['degreeid'],
                              $edu['fieldid'], $edu['grad_year'], $edu['program']);
@@ -254,7 +291,7 @@ class ProfileEdu implements ProfileSetting
     }
 }
 
-class ProfileEmailDirectory implements ProfileSetting
+class ProfileSettingEmailDirectory implements ProfileSetting
 {
     public function __construct(){}
     public function save(ProfilePage &$page, $field, $value){}
@@ -279,7 +316,7 @@ class ProfileEmailDirectory implements ProfileSetting
     }
 }
 
-class ProfileNetworking implements ProfileSetting
+class ProfileSettingNetworking implements ProfileSetting
 {
     private $email;
     private $pub;
@@ -288,25 +325,24 @@ class ProfileNetworking implements ProfileSetting
 
     public function __construct()
     {
-        $this->email  = new ProfileEmail();
-        $this->pub    = new ProfilePub();
-        $this->web    = new ProfileWeb();
-        $this->number = new ProfileNumber();
+        $this->email  = new ProfileSettingEmail();
+        $this->pub    = new ProfileSettingPub();
+        $this->web    = new ProfileSettingWeb();
+        $this->number = new ProfileSettingNumber();
     }
 
     public function value(ProfilePage &$page, $field, $value, &$success)
     {
         if (is_null($value)) {
-            $value = XDB::fetchAllAssoc("SELECT  n.address, n.network_type AS type, n.pub, m.name
+            $value = XDB::fetchAllAssoc("SELECT  n.address, n.pub, n.nwid AS type
                                            FROM  profile_networking AS n
-                                     INNER JOIN  profile_networking_enum AS m ON (n.network_type = m.network_type)
-                                          WHERE  n.uid = {?}",
+                                          WHERE  n.pid = {?}",
                                          $page->pid());
         }
         if (!is_array($value)) {
             $value = array();
         }
-        $filters = XDB::fetchAllAssoc('type', 'SELECT  filter, network_type AS type
+        $filters = XDB::fetchAllAssoc('type', 'SELECT  filter, nwid AS type, name
                                                  FROM  profile_networking_enum;');
         $success = true;
         foreach($value as $i=>&$network) {
@@ -319,11 +355,12 @@ class ProfileNetworking implements ProfileSetting
                 $network['error'] = false;
                 $network['pub'] = $this->pub->value($page, 'pub', $network['pub'], $s);
                 $s = true;
-                if ($filters[$network['type']] == 'web') {
+                $network['name'] = $filters[$network['type']]['name'];
+                if ($filters[$network['type']]['filter'] == 'web') {
                     $network['address'] = $this->web->value($page, 'address', $network['address'], $s);
-                } elseif ($filters[$network['type']] == 'email') {
+                } elseif ($filters[$network['type']]['filter'] == 'email') {
                     $network['address'] = $this->email->value($page, 'address', $network['address'], $s);
-                } elseif ($filters[$network['type']] == 'number') {
+                } elseif ($filters[$network['type']]['filter'] == 'number') {
                     $network['address'] = $this->number->value($page, 'address', $network['address'], $s);
                 }
                 if (!$s) {
@@ -338,21 +375,95 @@ class ProfileNetworking implements ProfileSetting
     public function save(ProfilePage &$page, $field, $value)
     {
         XDB::execute("DELETE FROM profile_networking
-                            WHERE uid = {?}",
+                            WHERE pid = {?}",
                      $page->pid());
         if (!count($value)) {
             return;
         }
         $insert = array();
         foreach ($value as $id=>$network) {
-            XDB::execute("INSERT INTO  profile_networking (uid, nwid, network_type, address, pub)
+            XDB::execute("INSERT INTO  profile_networking (pid, id, nwid, address, pub)
                                VALUES  ({?}, {?}, {?}, {?}, {?})",
                          $page->pid(), $id, $network['type'], $network['address'], $network['pub']);
         }
     }
 }
 
-class ProfileGeneral extends ProfilePage
+class ProfileSettingPromo implements ProfileSetting
+{
+    public function __construct(){}
+
+    public function save(ProfilePage &$page, $field, $value)
+    {
+        $gradYearNew = $value;
+        if ($page->profile->mainEducation() == 'X') {
+            $gradYearNew += $page->profile->mainEducationDuration();
+        }
+        if (($page->profile->mainEducation() != 'X'
+             && $value == $page->profile->entry_year + $page->profile->mainEducationDuration())
+           || ($page->profile->mainEducation() == 'X' && $value == $page->profile->entry_year)) {
+            XDB::execute('UPDATE  profile_display
+                             SET  promo = {?}
+                           WHERE  pid = {?}',
+                         $page->profile->mainEducation() . strval($value), $page->profile->id());
+            XDB::execute('UPDATE  profile_education
+                             SET  grad_year = {?}
+                           WHERE  pid = {?} AND FIND_IN_SET(\'primary\', flags)',
+                         $gradYearNew, $page->profile->id());
+            Platal::page()->trigSuccess('Ton statut « orange » a été supprimé.');
+        } else {
+            require_once 'validations.inc.php';
+
+            $myorange = new OrangeReq(S::user(), $gradYearNew);
+            $myorange->submit();
+            Platal::page()->trigSuccess('Tu pourras changer l\'affichage de ta promotion dès que ta nouvelle promotion aura été validée.');
+        }
+    }
+
+    public function value(ProfilePage &$page, $field, $value, &$success)
+    {
+        $entryYear = $page->profile->entry_year;
+        $gradYear  = $page->profile->grad_year;
+        $yearpromo = $page->profile->grad_year;
+        if ($page->profile->mainEducation() == 'X') {
+            $yearpromo -= $page->profile->mainEducationDuration();
+        }
+        $success   = true;
+        if (is_null($value) || $value == $yearpromo) {
+            if ($gradYear != $entryYear + $page->profile->mainEducationDuration()) {
+                $promoChoice = array();
+                for ($i = $entryYear; $i <= $gradYear - $page->profile->mainEducationDuration(); ++$i) {
+                    if ($page->profile->mainEducation() == 'X') {
+                        $promoChoice[] = $page->profile->mainEducation() . strval($i);
+                    } else {
+                        $promoChoice[] = $page->profile->mainEducation() . strval($i + $page->profile->mainEducationDuration());
+                    }
+                }
+                Platal::page()->assign('promo_choice', $promoChoice);
+            }
+            return $yearpromo;
+        }
+
+        // If this profile belongs to an X, $promoNew needs to be changed to
+        // the graduation year.
+        $gradYearNew = $value;
+        if ($page->profile->mainEducation() == 'X') {
+            $gradYearNew += $page->profile->mainEducationDuration();
+        }
+
+        if ($value < 1000 || $value > 9999) {
+            Platal::page()->trigError('L\'année de sortie doit être un nombre de quatre chiffres.');
+            $success = false;
+        } elseif ($gradYearNew < $entryYear + $page->profile->mainEducationDuration()) {
+            Platal::page()->trigError('Trop tôt&nbsp;!');
+            $success = false;
+        }
+        return intval($value);
+    }
+}
+
+
+class ProfileSettingGeneral extends ProfilePage
 {
     protected $pg_template = 'profile/general.tpl';
 
@@ -360,25 +471,26 @@ class ProfileGeneral extends ProfilePage
     {
         parent::__construct($wiz);
         $this->settings['search_names']
-                                  = new ProfileSearchNames();
-        $this->settings['birthdate'] = new ProfileDate();
+                                  = new ProfileSettingSearchNames();
+        $this->settings['birthdate'] = new ProfileSettingDate();
         $this->settings['freetext_pub']
                                   = $this->settings['photo_pub']
-                                  = new ProfilePub();
+                                  = new ProfileSettingPub();
         $this->settings['freetext']
                                   = $this->settings['nationality1']
                                   = $this->settings['nationality2']
                                   = $this->settings['nationality3']
                                   = $this->settings['yourself']
-                                  = $this->settings['promo']
+                                  = $this->settings['promo_display']
                                   = null;
         $this->settings['email_directory']
-                                  = new ProfileEmail();
+                                  = new ProfileSettingEmail();
         $this->settings['email_directory_new']
-                                  = new ProfileEmailDirectory();
-        $this->settings['networking'] = new ProfileNetworking();
-        $this->settings['tels']   = new ProfilePhones('user', 0);
-        $this->settings['edus']   = new ProfileEdu();
+                                  = new ProfileSettingEmailDirectory();
+        $this->settings['networking'] = new ProfileSettingNetworking();
+        $this->settings['tels']   = new ProfileSettingPhones('user', 0);
+        $this->settings['edus']   = new ProfileSettingEdu();
+        $this->settings['promo']  = new ProfileSettingPromo();
         $this->watched= array('freetext' => true, 'tels' => true,
                               'networking' => true, 'edus' => true,
                               'nationality1' => true, 'nationality2' => true,
@@ -388,17 +500,14 @@ class ProfileGeneral extends ProfilePage
     protected function _fetchData()
     {
         // Checkout all data...
-        $res = XDB::query("SELECT  p.promo, e.entry_year AS entry_year, e.grad_year AS grad_year,
-                                   pr.nationality1, pr.nationality2, pr.nationality3, pr.birthdate,
-                                   t.display_tel as mobile, t.pub as mobile_pub,
-                                   d.email_directory as email_directory,
-                                   pr.freetext, pr.freetext_pub, pr.ax_id AS matricule_ax, p.yourself
-                             FROM  profiles              AS pr
-                       INNER JOIN  profile_display       AS p ON (p.pid = pr.pid)
-                       INNER JOIN  profile_education     AS e ON (e.uid = pr.pid AND FIND_IN_SET('primary', e.flags))
-                        LEFT JOIN  profile_phones        AS t ON (t.uid = pr.pid AND link_type = 'user')
-                        LEFT JOIN  profile_directory     AS d ON (d.uid = pr.pid)
-                            WHERE  pr.pid = {?}", $this->pid());
+        $res = XDB::query("SELECT  p.nationality1, p.nationality2, p.nationality3, p.birthdate,
+                                   pp.display_tel as mobile, pp.pub as mobile_pub,
+                                   p.email_directory as email_directory, pd.promo AS promo_display,
+                                   p.freetext, p.freetext_pub, p.ax_id AS matricule_ax, pd.yourself
+                             FROM  profiles              AS p
+                       INNER JOIN  profile_display       AS pd ON (pd.pid = p.pid)
+                        LEFT JOIN  profile_phones        AS pp ON (pp.pid = p.pid AND link_type = 'user')
+                            WHERE  p.pid = {?}", $this->pid());
         $this->values = $res->fetchOneAssoc();
         if ($this->owner) {
             $this->values['yourself'] = $this->owner->displayName();
@@ -413,25 +522,19 @@ class ProfileGeneral extends ProfilePage
         if ($this->owner) {
             $res = XDB::query("SELECT  COUNT(*)
                                  FROM  requests
-                                WHERE  type='photo' AND user_id = {?}",
+                                WHERE  type = 'photo' AND uid = {?}",
                               $this->owner->id());
             $this->values['nouvellephoto'] = $res->fetchOneCell();
         } else {
             $this->values['nouvellephoto'] = 0;
         }
-
-        // Proposes choice for promotion
-        if ($this->values['entry_year'] != $this->values['grad_year'] - 3) {
-            for ($i = $this->values['entry_year']; $i < $this->values['grad_year'] - 2; $i++) {
-                $this->values['promo_choice'][] = "X" . $i;
-            }
-        }
     }
 
     protected function _saveData()
     {
         if ($this->changed['nationality1'] || $this->changed['nationality2'] || $this->changed['nationality3']
-            || $this->changed['birthdate'] || $this->changed['freetext'] || $this->changed['freetext_pub']) {
+            || $this->changed['birthdate'] || $this->changed['freetext'] || $this->changed['freetext_pub']
+            || $this->changed['email_directory']) {
             if ($this->values['nationality3'] == "") {
                 $this->values['nationality3'] = NULL;
             }
@@ -444,24 +547,19 @@ class ProfileGeneral extends ProfilePage
                 $this->values['nationality2'] = $this->values['nationality3'];
                 $this->values['nationality3'] = NULL;
             }
+            $new_email = ($this->values['email_directory'] == "new@example.org") ?
+                $this->values['email_directory_new'] : $this->values['email_directory'];
+            if ($new_email == "") {
+                $new_email = NULL;
+            }
 
             XDB::execute("UPDATE  profiles
                              SET  nationality1 = {?}, nationality2 = {?}, nationality3 = {?}, birthdate = {?},
-                                  freetext = {?}, freetext_pub = {?}
+                                  freetext = {?}, freetext_pub = {?}, email_directory = {?}
                            WHERE  pid = {?}",
                           $this->values['nationality1'], $this->values['nationality2'], $this->values['nationality3'],
                           preg_replace('@(\d{2})/(\d{2})/(\d{4})@', '\3-\2-\1', $this->values['birthdate']),
-                          $this->values['freetext'], $this->values['freetext_pub'], $this->pid());
-        }
-        if ($this->changed['email_directory']) {
-            $new_email = ($this->values['email_directory'] == "new@example.org") ?
-                $this->values['email_directory_new'] : $this->values['email_directory'];
-            if ($new_email == "") {
-                $new_email = NULL;
-            }
-            XDB::execute("REPLACE INTO  profile_directory (uid, email_directory)
-                                VALUES  ({?}, {?})",
-                         $this->pid(), $new_email);
+                          $this->values['freetext'], $this->values['freetext_pub'], $new_email, $this->pid());
         }
         if ($this->changed['photo_pub']) {
             XDB::execute("UPDATE  profile_photos
@@ -470,15 +568,29 @@ class ProfileGeneral extends ProfilePage
                          $this->values['photo_pub'], $this->pid());
         }
         if ($this->changed['yourself']) {
-            XDB::execute('UPDATE  accounts
-                             SET  display_name = {?}
-                           WHERE  pid = {?}', $this->pid());
+            if ($this->owner) {
+                XDB::execute('UPDATE  accounts
+                                 SET  display_name = {?}
+                               WHERE  uid = {?}',
+                             $this->values['yourself'], $this->owner->id());
+            }
+            XDB::execute('UPDATE  profile_display
+                             SET  yourself = {?}
+                           WHERE  pid = {?}', $this->values['yourself'],
+                         $this->pid());
         }
-        if ($this->changed['promo']) {
-            XDB::execute("UPDATE  profile_display
-                             SET  promo = {?}
-                           WHERE  pid = {?}",
-                         $this->values['promo'], $this->pid());
+        if ($this->changed['promo_display']) {
+            if ($this->values['promo_display']{0} == $this->profile->mainEducation()) {
+                if (($this->profile->mainEducation() == 'X'
+                     && intval(substr($this->values['promo_display'], 1, 4)) >= $this->profile->entry_year)
+                    || ($this->profile->mainEducation() != 'X'
+                        && intval(substr($this->values['promo_display'], 1, 4)) >= $this->profile->entry_year + $this->profile->mainEducationDuration())) {
+                    XDB::execute('UPDATE  profile_display
+                                     SET  promo = {?}
+                                   WHERE  pid = {?}',
+                                 $this->values['promo_display'], $this->pid());
+                }
+            }
         }
     }
 
@@ -494,7 +606,7 @@ class ProfileGeneral extends ProfilePage
         require_once "emails.combobox.inc.php";
         fill_email_combobox($page, $this->owner, $this->profile);
 
-        $res = XDB::query("SELECT  nw.network_type AS type, nw.name
+        $res = XDB::query("SELECT  nw.nwid AS type, nw.name
                              FROM  profile_networking_enum AS nw
                          ORDER BY  name");
         $page->assign('network_list', $res->fetchAllAssoc());
@@ -506,6 +618,7 @@ class ProfileGeneral extends ProfilePage
         $res = $res->fetchOneRow();
         $page->assign('public_name', $res[0]);
         $page->assign('private_name', $res[1]);
+        $page->assign('isFemale', $this->profile->isFemale() ? 1 : 0);
     }
 }