Adapts homonyms issues to new mail chain.
[platal.git] / modules / register / register.inc.php
index 6aaf67f..bd6f860 100644 (file)
@@ -1,6 +1,6 @@
 <?php
 /***************************************************************************
- *  Copyright (C) 2003-2009 Polytechnique.org                              *
+ *  Copyright (C) 2003-2011 Polytechnique.org                              *
  *  http://opensource.polytechnique.org/                                   *
  *                                                                         *
  *  This program is free software; you can redistribute it and/or modify   *
  *  59 Temple Place, Suite 330, Boston, MA  02111-1307  USA                *
  ***************************************************************************/
 
-// {{{ function user_cmp
+// {{{ function checkId
 
-function user_cmp($prenom, $nom, $_prenom, $_nom)
+function checkId($subState)
 {
-    $_nom    = mb_strtoupper($_nom);
-    $_prenom = mb_strtoupper($_prenom);
-    $nom     = mb_strtoupper($nom);
-    $prenom  = mb_strtoupper($prenom);
-
-    $is_ok   = mb_strtoupper($_prenom) == mb_strtoupper($prenom);
-
-    $tokens  = preg_split("/[ \-']/", $nom, -1, PREG_SPLIT_NO_EMPTY);
-    $maxlen  = 0;
-
-    foreach ($tokens as $str) {
-        $is_ok &= strpos($_nom, $str)!==false;
-        $maxlen = max($maxlen, strlen($str));
+    $subState->set('xorgid', Profile::getXorgId($subState->i('schoolid')));
+    if (!$subState->v('xorgid')) {
+        return 'Le matricule est incorrect.';
     }
 
-    return $is_ok && ($maxlen > 2 || $maxlen == strlen($_nom));
-}
-
-// }}}
-// {{{ function check_mat
-
-function check_mat($promo, $mat, &$nom, &$prenom, &$ourmat, &$ourid, &$watch, &$naiss)
-{
-    if (!preg_match('/^[0-9][0-9][0-9][0-9][0-9][0-9]$/', $mat)) {
-        return "Le matricule doit comporter 6 chiffres.";
+    $uf = new UserFilter(new PFC_And(
+            new UFC_SchoolId('xorg', $subState->i('xorgid')),
+            new PFC_Not(new UFC_Dead()),
+            new PFC_Not(new UFC_Registered(true))
+    ));
+    $profile = $uf->getProfile();
+    if (is_null($profile)) {
+        return "Tu es déjà inscrit ou ton matricule est incorrect !";
     }
 
-    $year = intval(substr($mat, 0, 3));
-    $rang = intval(substr($mat, 3, 3));
-    if ($year > 200) { $year /= 10; };
-    if ($year < 96) {
-        return "ton matricule est incorrect";
-    } else {
-        $ourmat = sprintf('%04u%04u', 1900+$year, $rang);
+    if ($profile->promo() != $subState->s('promo')) {
+        return 'Le matricule est incorrect.';
     }
 
-    $res = XDB::query(
-            'SELECT  user_id, promo, perms IN ("admin","user"), nom, prenom, FIND_IN_SET(\'watch\', flags), naissance_ini
-              FROM  auth_user_md5
-             WHERE  matricule={?} and deces = 0', $ourmat);
-    list ($uid, $_promo, $_already, $_nom, $_prenom, $watch, $naiss) = $res->fetchOneRow();
-    if ($_already) { return "tu es déjà inscrit ou ton matricule est incorrect !"; }
-    if ($_promo != $promo) { return "erreur de matricule"; }
-
-    if (!user_cmp($prenom, $nom, $_prenom, $_nom)) {
-        return "erreur dans l'identification.  Réessaie, il y a une erreur quelque part !";
+    if (!$profile->compareNames($subState->s('firstname'), $subState->s('lastname'))) {
+        return "Erreur dans l'identification. Réessaie, il y a une erreur quelque part !";
     }
 
-    $nom = $_nom;
-    $prenom = $_prenom;
-    $ourid = $uid;
+    $subState->set('lastname', $profile->lastName());
+    $subState->set('firstname', $profile->firstName());
+    $subState->set('uid', $profile->owner()->id());
+    $subState->set('watch', $profile->owner()->watch);
+    $subState->set('birthdateRef', $profile->__get('birthdate_ref'));
     return true;
 }
 
 // }}}
-// {{{ function check_old_mat
+// {{{ function checkOldId
 
-function check_old_mat($promo, $mat, &$nom, &$prenom, &$ourmat, &$ourid, &$watch, &$naiss)
+function checkOldId($subState)
 {
-    $res = XDB::iterRow(
-            'SELECT  user_id, nom, prenom, matricule, FIND_IN_SET(\'watch\', flags), naissance_ini
-               FROM  auth_user_md5
-              WHERE  promo={?} AND deces=0 AND perms="pending"', $promo);
-    while (list($_uid, $_nom, $_prenom, $_mat, $watch, $naiss) = $res->next()) {
-        if (user_cmp($prenom, $nom, $_prenom, $_nom)) {
-            $nom = $_nom;
-            $prenom = $_prenom;
-            $ourid  = $_uid;
-            $ourmat = $_mat;
+    $uf = new UserFilter(new PFC_And(
+            new PFC_Not(new UFC_Dead()),
+            new UFC_Promo('=', UserFilter::DISPLAY, $subState->s('promo')),
+            new PFC_Not(new UFC_Registered(true))
+    ));
+    $it = $uf->iterProfiles();
+    while ($profile = $it->next()) {
+        if ($profile->compareNames($subState->s('firstname'), $subState->s('lastname'))) {
+            $subState->set('lastname', $profile->lastName());
+            $subState->set('firstname', $profile->firstName());
+            $subState->set('uid', $profile->owner()->id());
+            $subState->set('watch', $profile->owner()->watch);
+            $subState->set('birthdateRef', $profile->__get('birthdate_ref'));
+            $subState->set('xorgid', $profile->__get('xorg_id'));
             return true;
         }
     }
 
-    $res = XDB::iterRow(
-            'SELECT  user_id, nom, prenom, matricule, alias, FIND_IN_SET(\'watch\', u.flags), naissance_ini
-               FROM  auth_user_md5 AS u
-         INNER JOIN  aliases       AS a ON (u.user_id = a.id and FIND_IN_SET("bestalias", a.flags))
-              WHERE  promo={?} AND deces=0 AND perms IN ("user","admin")', $promo);
-    while (list($_uid, $_nom, $_prenom, $_mat, $alias, $watch, $naiss) = $res->next()) {
-        if (user_cmp($prenom, $nom, $_prenom, $_nom)) {
-            $ourid  = $_uid;
-            $ourmat = $_mat;
-            return "Tu es vraisemblablement déjà inscrit !";
+    $uf = new UserFilter(new PFC_And(
+            new PFC_Not(new UFC_Dead()),
+            new UFC_Promo('=', UserFilter::DISPLAY, $subState->s('promo')),
+            new UFC_Registered(true)
+    ));
+    $it = $uf->iterProfiles();
+    while ($profile = $it->next()) {
+        if ($profile->compareNames($subState->s('firstname'), $subState->s('lastname'))) {
+            $subState->set('uid', $profile->owner()->id());
+            $subState->set('watch', $profile->owner()->watch);
+            $subState->set('birthdateRef', $profile->__get('birthdate_ref'));
+            $subState->set('xorgid', $profile->__get('xorg_id'));
+            return 'Tu es vraisemblablement déjà inscrit !';
         }
     }
-    return "erreur: vérifie que tu as bien orthographié ton nom !";
+    return 'Erreur : vérifie que tu as bien orthographié ton nom !';
 }
 
 // }}}
-// {{{ function check_new_user
+// {{{ function checkNewUser
 
-function check_new_user(&$sub)
+function checkNewUser($subState)
 {
-    extract($sub);
-
-    $prenom  = preg_replace("/[ \t]+/", ' ', trim($prenom));
-    $prenom  = preg_replace("/--+/", '-', $prenom);
-    $prenom  = preg_replace("/''+/", '\'', $prenom);
-    $prenom  = make_firstname_case($prenom);
-
-    $nom     = preg_replace("/[ \t]+/", ' ', trim($nom));
-    $nom     = preg_replace("/--+/", '-', $nom);
-    $nom     = preg_replace("/''+/", '\'', $nom);
-    $nom     = mb_strtoupper($nom);
-
-    if ($promo >= 1996) {
-        $res = check_mat($promo, $mat, $nom, $prenom, $ourmat, $ourid, $watch, $naiss);
+    $firstname = preg_replace("/[ \t]+/", ' ', $subState->t('firstname'));
+    $firstname = preg_replace("/--+/", '-', $firstname);
+    $firstname = preg_replace("/''+/", '\'', $firstname);
+    $subState->set('firstname', PlUser::fixFirstnameCase($firstname));
+
+    $lastname = preg_replace("/[ \t]+/", ' ', $subState->t('lastname'));
+    $lastname = preg_replace("/--+/", '-', $lastname);
+    $lastname = preg_replace("/''+/", '\'', $lastname);
+    $subState->set('lastname', mb_strtoupper($lastname));
+
+    if ($subState->i('yearpromo') >= 1996) {
+        $res = checkId($subState);
     } else {
-        $res = check_old_mat($promo, $mat, $nom, $prenom, $ourmat, $ourid, $watch, $naiss);
+        $res = checkOldId($subState);
+    }
+    if ($res !== true) {
+        return $res;
     }
-    if ($res !== true) { return $res; }
-
-    $sub['nom']    = $nom;
-    $sub['prenom'] = $prenom;
-    $sub['ourmat'] = $ourmat;
-    $sub['uid']    = $ourid;
-    $sub['watch']  = $watch;
-    $sub['naissance_ini'] = $naiss;
 
     return true;
 }
 
 // }}}
-// {{{ function create_aliases
+// {{{ function createAliases
 
-function create_aliases (&$sub)
+function createAliases($subState)
 {
     global $globals;
-    extract ($sub);
 
-    $mailorg = make_username($prenom, $nom);
-    $mailorg2 = $mailorg.sprintf(".%02u", ($promo%100));
+    $emailXorg  = PlUser::makeUserName($subState->t('firstname'), $subState->t('lastname'));
+    $emailXorg2 = $emailXorg . sprintf(".%02u", ($subState->i('yearpromo') % 100));
 
-    $res = XDB::query("SELECT hruid FROM auth_user_md5 WHERE user_id = {?} AND hruid != ''", $uid);
+    $res = XDB::query("SELECT  hruid, state
+                         FROM  accounts
+                        WHERE  uid = {?} AND hruid != ''",
+                      $subState->i('uid'));
     if ($res->numRows() == 0) {
         return "Tu n'as pas d'adresse à vie pré-attribuée.<br />"
-            . "Envoie un mail à <a href=\"mailto:support@{$globals->mail->domain}</a>\">"
+            . "Envoie un mail à <a href=\"mailto:support@{$globals->mail->domain}\">"
             . "support@{$globals->mail->domain}</a> en expliquant ta situation.";
     } else {
-        // TODO: at the moment forlife == hruid, however we'll have to change
-        // that behaviour when masters will be on plat/al.
-        $forlife = $res->fetchOneCell();
+        list($forlife, $state) = $res->fetchOneRow();
+    }
+    if ($state == 'active') {
+        return "Tu es déjà inscrit, si tu ne te souviens plus de ton mot de passe d'accès au site, "
+             . "tu peux suivre <a href=\"recovery\">la procédure de récupération de mot de passe</a>.";
+    } else if ($state == 'disabled') {
+        return "Ton compte a été désactivé par les administrateurs du site suite à des abus. "
+             . "Pour plus d'information ou pour demander la réactivation du compte, tu peux t'adresser à "
+             . "<a href=\"mailto:support@{$globals->mail->domain}\">support@{$globals->mail->domain}</a>.";
     }
 
-    $res = XDB::query('SELECT id, type, expire FROM aliases WHERE alias={?}', $mailorg);
-    if ($res->numRows()) {
+    $count = XDB::numRows('SELECT  *
+                             FROM  email_source_account  AS s
+                       INNER JOIN  email_virtual_domains AS d ON (s.domain = d.id)
+                            WHERE  s.email = {?} AND d.name = {?}',
+                          $emailXorg, $globals->mail->domain);
+    if ($count) {
         list($h_id, $h_type, $expire) = $res->fetchOneRow();
         if ($h_type != 'homonyme' and empty($expire)) {
-            XDB::execute('UPDATE aliases SET expire=ADDDATE(NOW(),INTERVAL 1 MONTH) WHERE alias={?}', $mailorg);
-            XDB::execute('REPLACE INTO homonymes (homonyme_id,user_id) VALUES ({?},{?})', $h_id, $h_id);
-            XDB::execute('REPLACE INTO homonymes (homonyme_id,user_id) VALUES ({?},{?})', $h_id, $uid);
-            $res = XDB::query("SELECT alias FROM aliases WHERE id={?} AND expire IS NULL", $h_id);
-            $als = $res->fetchColumn();
-
-            $mailer = new PlMailer();
-            $mailer->setFrom('"Support Polytechnique.org" <support@' . $globals->mail->domain . '>');
-            $mailer->addTo("$mailorg@" . $globals->mail->domain);
-            $mailer->setSubject("perte de ton alias $mailorg dans un mois !");
-            $mailer->addCc('"Support Polytechnique.org" <support@' . $globals->mail->domain . '>');
-            $msg =
-                "Bonjour,\n\n".
-
-                "Un homonyme vient de s'inscrire. La politique de Polytechnique.org est de fournir des\n".
-                "adresses email devinables, nous ne pouvons donc pas conserver ton alias '$mailorg' qui\n".
-                "correspond maintenant à deux personnes.\n\n".
-
-                "Tu gardes tout de même l'usage de cet alias pour un mois encore à compter de ce jour.\n\n".
-
-                "Lorsque cet alias sera désactivé, l'adresse $mailorg@polytechnique.org renverra vers un \n".
-                "robot qui indiquera qu'il y a plusieurs personnes portant le même nom ;\n".
-                "cela évite que l'un des homonymes reçoive des courriels destinés à l'autre.\n\n".
-
-                "Pour te connecter au site, tu pourras utiliser comme identifiant n'importe lequel de tes\n".
-                "autres alias :\n".
-                "    ".join(', ', $als)."\n";
-                "Commence dès aujourd'hui à communiquer à tes correspondants la nouvelle adresse que tu comptes utiliser !\n\n".
-
-                "En nous excusant pour le désagrément occasionné,\n".
-                "Cordialement,\n\n".
-
-                "-- \n".
-                "L'équipe de Polytechnique.org\n".
-                "\"Le portail des élèves & anciens élèves de l'X\"";
+            XDB::execute('UPDATE  email_source_account  AS e
+                      INNER JOIN  email_virtual_domains AS d ON (e.domain = d.id)
+                             SET  e.expire = ADDDATE(NOW(), INTERVAL 1 MONTH)
+                           WHERE  e.email = {?} AND d.name = {?}',
+                         $emailXorg, $globals->mail->domain);
+            $hrmid = 'h.' . $emailXorg . '.' . $globals->mail->domain;
+            XDB::execute('INSERT IGNORE INTO  homonyms_list (hrmid, uid)
+                                      VALUES  ({?}, {?}), ({?}, {?})',
+                         $hrmid, $h_id, $hrmid, $subState->i('uid'));
+            $als = XDB::fetchColumn('SELECT  *
+                                       FROM  email_source_account  AS s
+                                 INNER JOIN  email_virtual_domains AS d ON (s.domain = d.id)
+                                      WHERE  s.uid = {?} AND d.name = {?} AND s.expire IS NULL',
+                                    $h_id, $globals->mail->domain);
+
+            $mailer = new PlMailer('register/lostalias.mail.tpl');
+            $mailer->addTo($emailXorg . '@' . $globals->mail->domain);
+            $mailer->setSubject("Perte de ton alias $emailXorg dans un mois !");
+            $mailer->assign('emailXorg', $emailXorg);
+            $mailer->assign('als', join(', ', $als));
             $mailer->SetTxtBody(wordwrap($msg,72));
             $mailer->send();
         }
 
-        $sub['forlife']   = $forlife;
-        $sub['bestalias'] = $mailorg2;
-        $sub['mailorg2']  = null;
+        $subState->set('forlife', $forlife);
+        $subState->set('bestalias', $emailXorg2);
+        $subState->set('emailXorg2', null);
     } else {
-        $sub['forlife']   = $forlife;
-        $sub['bestalias'] = $mailorg;
-        $sub['mailorg2']  = $mailorg2;
+        $subState->set('forlife', $forlife);
+        $subState->set('bestalias', $emailXorg);
+        $subState->set('emailXorg2', $emailXorg2);
     }
 
     return true;
 }
 
 // }}}
-// {{{ function finish_ins
+// {{{ function finishRegistration
 
-function finish_ins($sub_state)
+function finishRegistration($subState)
 {
     global $globals;
-    extract($sub_state);
 
     $hash = rand_url_id(12);
-    XDB::execute(
-            "UPDATE  auth_user_md5
-                SET  last_known_email = {?}
-              WHERE  matricule = {?}", $email, $mat);
-    XDB::execute(
-            "REPLACE INTO  register_pending (uid, forlife, bestalias, mailorg2, password, email, date, relance, naissance, hash, services)
-                   VALUES  ({?}, {?}, {?}, {?}, {?}, {?}, NOW(), 0, {?}, {?}, {?})",
-            $uid, $forlife, $bestalias, $mailorg2, $password, $email, $naissance, $hash, implode(',', $services));
-
-    $mymail = new PlMailer('register/inscrire.mail.tpl');
-    $mymail->assign('mailorg', $bestalias);
-    $mymail->assign('lemail',  $email);
+    XDB::execute('INSERT INTO  register_pending (uid, forlife, bestalias, mailorg2, password,
+                                                 email, date, relance, naissance, hash, services)
+                              VALUES  ({?}, {?}, {?}, {?}, {?}, {?}, NOW(), 0, {?}, {?}, {?})
+                              ON DUPLICATE KEY UPDATE password=VALUES(password), email=VALUES(email),
+                                                      date=VALUES(date), naissance=VALUES(naissance),
+                                                      hash=VALUES(hash), services=VALUES(services)',
+                 $subState->i('uid'), $subState->s('forlife'), $subState->s('bestalias'),
+                 $subState->s('emailXorg2'), $subState->s('password'), $subState->s('email'),
+                 $subState->s('birthdate'), $hash, implode(',', $subState->v('services')));
+
+    $mymail = new PlMailer('register/end.mail.tpl');
+    $mymail->assign('emailXorg', $subState->s('bestalias'));
+    $mymail->assign('to', $subState->s('email'));
     $mymail->assign('baseurl', $globals->baseurl);
-    $mymail->assign('hash',    $hash);
-    $mymail->assign('subj',    $bestalias."@" . $globals->mail->domain);
+    $mymail->assign('hash', $hash);
+    $mymail->assign('subject', $subState->s('bestalias') . '@' . $globals->mail->domain);
     $mymail->send();
 }