2 /***************************************************************************
3 * Copyright (C) 2003-2011 Polytechnique.org *
4 * http://opensource.polytechnique.org/ *
6 * This program is free software; you can redistribute it and/or modify *
7 * it under the terms of the GNU General Public License as published by *
8 * the Free Software Foundation; either version 2 of the License, or *
9 * (at your option) any later version. *
11 * This program is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU General Public License for more details. *
16 * You should have received a copy of the GNU General Public License *
17 * along with this program; if not, write to the Free Software *
19 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
20 ***************************************************************************/
22 class RegisterModule
extends PLModule
27 'register' => $this->make_hook('register', AUTH_PUBLIC
),
28 'register/end' => $this->make_hook('end', AUTH_PUBLIC
),
32 function handler_register($page, $hash = null
)
36 $subState = new PlDict(S
::v('subState', array()));
37 if (!$subState->has('step')) {
38 $subState->set('step', 0);
40 if (!$subState->has('backs')) {
41 $subState->set('backs', new PlDict());
43 if (Get
::has('back') && Get
::i('back') < $subState->i('step')) {
44 $subState->set('step', max(0, Get
::i('back')));
45 $subState->v('backs')->set($subState->v('backs')->count() +
1, $subState->dict());
46 $subState->v('backs')->kill('backs');
47 if ($subState->v('backs')->count() == 3) {
48 $alert[] = "Tentative d'inscription très hésitante";
49 $alert_details .= "\n * Retours en arrières : 3.";
54 $res = XDB
::query("SELECT a.uid, a.hruid, ppn.lastname_initial AS lastname, ppn.firstname_initial AS firstname, p.xorg_id AS xorgid,
55 pd.promo, pe.promo_year AS yearpromo, pde.degree AS edu_type,
56 p.birthdate_ref AS birthdateRef, FIND_IN_SET('watch', a.flags) AS watch, m.hash, a.type, a.comment
57 FROM register_marketing AS m
58 INNER JOIN accounts AS a ON (m.uid = a.uid)
59 INNER JOIN account_profiles AS ap ON (a.uid = ap.uid AND FIND_IN_SET('owner', ap.perms))
60 INNER JOIN profiles AS p ON (p.pid = ap.pid)
61 INNER JOIN profile_display AS pd ON (p.pid = pd.pid)
62 INNER JOIN profile_education AS pe ON (pe.pid = p.pid AND FIND_IN_SET('primary', pe.flags))
63 INNER JOIN profile_education_degree_enum AS pde ON (pde.id = pe.degreeid)
64 INNER JOIN profile_public_names AS ppn ON (ppn.pid = p.pid)
65 WHERE m.hash = {?} AND a.state = 'pending'",
68 if ($res->numRows() == 1) {
69 $subState->merge($res->fetchOneRow());
70 $subState->set('main_mail_domain', User
::$sub_mail_domains[$subState->v('type')]);
72 XDB
::execute('INSERT INTO register_mstats (uid, sender, success)
73 SELECT m.uid, m.sender, 0
74 FROM register_marketing AS m
76 ON DUPLICATE KEY UPDATE sender = VALUES(sender), success = VALUES(success)',
77 $subState->s('hash'));
81 switch ($subState->i('step')) {
83 $wp = new PlWikiPage('Reference.Charte');
85 if (Post
::has('step1')) {
86 $subState->set('step', 1);
87 if ($subState->has('hash')) {
88 $subState->set('step', 3);
89 $this->load('register.inc.php');
90 createAliases($subState);
96 if (Post
::has('yearpromo')) {
97 $edu_type = Post
::t('edu_type');
98 $yearpromo = Post
::i('yearpromo');
99 $promo = Profile
::$cycle_prefixes[$edu_type] . $yearpromo;
100 $res = XDB
::query("SELECT COUNT(*)
102 INNER JOIN account_profiles AS ap ON (a.uid = ap.uid AND FIND_IN_SET('owner', ap.perms))
103 INNER JOIN profiles AS p ON (p.pid = ap.pid)
104 INNER JOIN profile_education AS pe ON (pe.pid = p.pid AND FIND_IN_SET('primary', pe.flags))
105 WHERE a.state = 'pending' AND p.deathdate IS NULL AND pe.promo_year = {?}",
108 if (!$res->fetchOneCell()) {
109 $error = 'La promotion saisie est incorrecte ou tous les camarades de cette promotion sont inscrits !';
111 $subState->set('step', 2);
112 $subState->set('promo', $promo);
113 $subState->set('yearpromo', $yearpromo);
114 $subState->set('edu_type', $edu_type);
115 if ($edu_type == Profile
::DEGREE_X
) {
116 if ($yearpromo >= 1996 && $yearpromo < 2000) {
117 $subState->set('schoolid', ($yearpromo %
100) * 10 . '???');
118 $subState->set('schoolid_exemple', ($yearpromo %
100) * 10000 +
532);
119 $subState->set('schoolid_exemple_ev2', (($yearpromo +
1) %
100) * 10000 +
532);
120 } elseif($yearpromo >= 2000) {
121 $subState->set('schoolid', 100 +
($yearpromo %
100) . '???');
122 $subState->set('schoolid_exemple', (100 +
($yearpromo %
100)) * 1000 +
532);
123 $subState->set('schoolid_exemple_ev2', (100 +
(($yearpromo +
1) %
100)) * 1000 +
532);
132 $this->load('register.inc.php');
133 $subState->set('firstname', Post
::t('firstname'));
134 $subState->set('lastname', Post
::t('lastname'));
135 if (Post
::has('schoolid')) {
136 $subState->set('schoolid', Post
::i('schoolid'));
138 $error = checkNewUser($subState);
140 if ($error !== true
) {
143 $error = createAliases($subState);
144 if ($error === true
) {
146 $subState->set('step', 3);
153 $this->load('register.inc.php');
155 // Validate the email address format and domain.
156 require_once 'emails.inc.php';
158 if (!isvalid_email(Post
::v('email'))) {
159 $error[] = "Le champ 'Email' n'est pas valide.";
160 } elseif (!isvalid_email_redirection(Post
::v('email'))) {
161 $error[] = $subState->s('forlife') . ' doit renvoyer vers un email existant '
162 . 'valide, en particulier, il ne peut pas être renvoyé vers lui-même.';
165 // Validate the birthday format and range.
166 $birth = Post
::t('birthdate');
167 if (!preg_match('@^[0-3]?\d/[01]?\d/(19|20)?\d{2}$@', $birth)) {
168 $error[] = "La 'Date de naissance' n'est pas correcte.";
170 $birth = explode('/', $birth, 3);
171 for ($i = 0; $i < 3; ++
$i)
172 $birth[$i] = intval($birth[$i]);
173 if ($birth[2] < 100) {
177 $ref_year = substr($subState->v('birthdateRef'), 0, 4);
178 if (abs($ref_year - $year) > 2) {
179 $error[] = "La 'Date de naissance' n'est pas correcte.";
180 $alert[] = "Date de naissance incorrecte à l'inscription";
181 $alert_details .= "\n * Date de naissance renseignée : " . Post
::t('birthdate') . ' (date connue : ' . $subState->v('birthdateRef') . ')';
182 $subState->set('wrong_birthdate', $birth);
186 // Register the optional services requested by the user.
188 foreach (array('ax_letter', 'imap', 'ml_promo', 'nl') as $service) {
189 if (Post
::b($service)) {
190 $services[] = $service;
193 $subState->set('services', $services);
195 // Validate the password.
196 if (!Post
::v('pwhash', false
)) {
197 $error[] = "Le mot de passe n'est pas valide.";
200 // Check if the given email is known as dangerous.
201 $res = XDB
::query("SELECT state, description
203 WHERE email = {?} AND state != 'safe'",
205 $bannedEmail = false
;
206 if ($res->numRows()) {
207 list($state, $description) = $res->fetchOneRow();
208 $alert[] = "Email surveillé proposé à l'inscription";
209 $alert_details .= "\n * Email surveillé : " . Post
::v('email');
210 $subState->set('email_desc', $description);
211 if ($state == 'dangerous') {
215 if ($subState->i('watch') != 0) {
216 $alert[] = "Inscription d'un utilisateur surveillé";
217 $alert_details .= "\n * Commentaire pour la surveillance : " . $subState->v('comment');
220 if (($bannedIp = check_ip('unsafe'))) {
225 $error = join('<br />', $error);
227 $subState->set('birthdate', sprintf("%04d-%02d-%02d",
228 intval($birth[2]), intval($birth[1]), intval($birth[0])));
229 $subState->set('email', Post
::t('email'));
230 $subState->set('password', Post
::t('pwhash'));
232 // Update the current alert if the birthdate is incorrect,
233 // or if the IP address of the user has been banned.
234 if ($subState->s('birthdateRef') != '0000-00-00'
235 && $subState->s('birthdateRef') != $subState->s('birthdate')) {
236 $alert[] = "Date de naissance incorrecte à l'inscription";
237 $alert_details .= "\n * Date de naissance renseignée : " . $subState->s('birthdate') . ' (date connue : ' . $subState->s('birthdateRef') . ')';
240 $alert[] = "Tentative d'inscription depuis une IP surveillée";
241 $alert_details .= "\n * IP surveillée : " . $_SESSION['check_ip'];
244 // Prevent banned user from actually registering; save the current state for others.
245 if ($bannedEmail ||
$bannedIp) {
247 $error = "Une erreur s'est produite lors de l'inscription."
248 . " Merci de contacter <a href='mailto:register@{$globals->mail->domain}>"
249 . " register@{$globals->mail->domain}</a>"
250 . " pour nous faire part de cette erreur.";
252 $subState->set('step', 4);
253 if ($subState->v('backs')->count() >= 3) {
254 $alert[] = "Fin d'une inscription hésitante";
255 $alert_details .= "\n * Nombre de retours en arrière : " . $subState->v('backs')->count();
257 finishRegistration($subState);
264 $_SESSION['subState'] = $subState->dict();
266 $alert_details = "Détails des alertes :" . $alert_details . "\n\n\n";
267 send_warning_mail(implode(' - ', $alert), $alert_details);
270 $page->changeTpl('register/step' . $subState->i('step') . '.tpl');
272 $page->trigError($error);
276 function handler_end($page, $hash = null
)
279 $_SESSION['subState'] = array('step' => 5);
281 // Reject registration requests from unsafe IP addresses (and remove the
282 // registration information from the database, to prevent IP changes).
283 if (check_ip('unsafe')) {
284 send_warning_mail('Une IP surveillée a tenté de finaliser son inscription.');
285 XDB
::execute("DELETE FROM register_pending
286 WHERE hash = {?} AND hash != 'INSCRIT'", $hash);
290 // Retrieve the pre-registration information using the url-provided
291 // authentication token.
292 $res = XDB
::query("SELECT r.uid, p.pid, r.forlife, r.bestalias, r.mailorg2,
293 r.password, r.email, r.services, r.naissance,
294 ppn.lastname_initial, ppn.firstname_initial, pe.promo_year,
295 pd.promo, p.sex, p.birthdate_ref, a.type
296 FROM register_pending AS r
297 INNER JOIN accounts AS a ON (r.uid = a.uid)
298 INNER JOIN account_profiles AS ap ON (a.uid = ap.uid AND FIND_IN_SET('owner', ap.perms))
299 INNER JOIN profiles AS p ON (p.pid = ap.pid)
300 INNER JOIN profile_public_names AS ppn ON (ppn.pid = p.pid)
301 INNER JOIN profile_display AS pd ON (p.pid = pd.pid)
302 INNER JOIN profile_education AS pe ON (pe.pid = p.pid AND FIND_IN_SET('primary', pe.flags))
303 WHERE hash = {?} AND hash != 'INSCRIT' AND a.state = 'pending'",
305 if (!$hash ||
$res->numRows() == 0) {
306 $page->kill("<p>Cette adresse n'existe pas, ou plus, sur le serveur.</p>
307 <p>Causes probables :</p>
309 <li>Vérifie que tu visites l'adresse du dernier
310 email reçu s'il y en a eu plusieurs.</li>
311 <li>Tu as peut-être mal copié l'adresse reçue par
312 email, vérifie-la à la main.</li>
313 <li>Tu as peut-être attendu trop longtemps pour
314 confirmer. Les pré-inscriptions sont annulées
315 tous les 30 jours.</li>
316 <li>Tu es en fait déjà inscrit.</li>
320 list($uid, $pid, $forlife, $bestalias, $emailXorg2, $password, $email, $services,
321 $birthdate, $lastname, $firstname, $yearpromo, $promo, $sex, $birthdate_ref, $type) = $res->fetchOneRow();
322 $isX = ($type == 'x');
323 $mail_domain = User
::$sub_mail_domains[$type] . $globals->mail
->domain
;
325 // Prepare the template for display.
326 $page->changeTpl('register/end.tpl');
327 $page->assign('forlife', $forlife);
328 $page->assign('firstname', $firstname);
330 // Check if the user did enter a valid password; if not (or if none is found),
331 // get her an information page.
332 if (Post
::has('response')) {
333 $expected_response = sha1("$forlife:$password:" . S
::v('challenge'));
334 if (Post
::v('response') != $expected_response) {
335 $page->trigError("Mot de passe invalide.");
336 S
::logger($uid)->log('auth_fail', 'bad password (register/end)');
344 // Create the user account.
346 XDB
::startTransaction();
347 XDB
::execute("UPDATE accounts
348 SET password = {?}, state = 'active',
349 registration_date = NOW(), email = NULL
350 WHERE uid = {?}", $password, $uid);
351 XDB
::execute("UPDATE profiles
352 SET birthdate = {?}, last_change = NOW()
353 WHERE pid = {?}", $birthdate, $pid);
354 XDB
::execute('INSERT INTO email_source_account (email, uid, type, flags, domain)
355 SELECT {?}, {?}, \'forlife\', \'\', id
356 FROM email_virtual_domains
358 $forlife, $uid, $mail_domain);
359 XDB
::execute('INSERT INTO email_source_account (email, uid, type, flags, domain)
360 SELECT {?}, {?}, \'alias\', \'bestalias\', id
361 FROM email_virtual_domains
363 $bestalias, $uid, $mail_domain);
365 XDB
::execute('INSERT INTO email_source_account (email, uid, type, flags, domain)
366 SELECT {?}, {?}, \'alias\', \'\', id
367 FROM email_virtual_domains
369 $emailXorg2, $uid, $mail_domain);
373 // Add the registration email address as first and only redirection.
374 require_once 'emails.inc.php';
375 $user = User
::getSilentWithUID($uid);
376 $redirect = new Redirect($user);
377 $redirect->add_email($email);
378 fix_bestalias($user);
380 // Try to start a session (so the user don't have to log in); we will use
381 // the password available in Post:: to authenticate the user.
382 Platal
::session()->start(AUTH_MDP
);
384 // Subscribe the user to the services she did request at registration time.
385 require_once 'newsletter.inc.php';
386 foreach (explode(',', $services) as $service) {
389 NewsLetter
::forGroup(NewsLetter
::GROUP_AX
)->subscribe($user);
392 NewsLetter
::forGroup(NewsLetter
::GROUP_XORG
)->subscribe($user);
395 Email
::activate_storage($user, 'imap', Bogo
::IMAP_DEFAULT
);
399 $r = XDB
::query('SELECT id FROM groups WHERE diminutif = {?}', $yearpromo);
401 $asso_id = $r->fetchOneCell();
402 XDB
::execute('INSERT IGNORE INTO group_members (uid, asso_id)
406 $mmlist = new MMList($user);
407 $mmlist->subscribe("promo" . $yearpromo);
408 } catch (Exception
$e) {
409 PlErrorReport
::report($e);
410 $page->trigError("L'inscription à la liste promo" . $yearpromo . " a échouée.");
418 // Log the registration in the user session.
419 S
::logger($uid)->log('inscription', $email);
420 XDB
::execute("UPDATE register_pending
422 WHERE uid = {?}", $uid);
424 // Congratulate our newly registered user by email.
425 $mymail = new PlMailer('register/success.mail.tpl');
426 $mymail->addTo("\"{$user->fullName()}\" <{$user->forlifeEmail()}>");
428 $mymail->setSubject('Bienvenue parmi les X sur le web !');
430 $mymail->setSubject('Bienvenue sur Polytechnique.org !');
432 $mymail->assign('forlife', $forlife);
433 $mymail->assign('firstname', $firstname);
436 // Index the user, to allow her to appear in searches.
437 Profile
::rebuildSearchTokens($pid);
439 // Notify other users which were watching for her arrival.
440 XDB
::execute('INSERT INTO contacts (uid, contact)
443 WHERE ni_id = {?}', $uid);
444 XDB
::execute('DELETE FROM watch_nonins
445 WHERE ni_id = {?}', $uid);
446 Platal
::session()->updateNbNotifs();
448 // Forcibly register the new user on default forums.
449 $registeredForums = array('xorg.general', 'xorg.pa.divers', 'xorg.pa.logements');
452 $promoForum = 'xorg.promo.' . strtolower($promo);
453 $exists = XDB
::fetchOneCell('SELECT COUNT(*)
459 // Notify the newsgroup admin of the promotion forum needs be created.
460 $promoFull = new UserFilter(new UFC_Promo('=', UserFilter
::DISPLAY
, $promo));
461 $promoRegistered = new UserFilter(new PFC_And(
462 new UFC_Promo('=', UserFilter
::DISPLAY
, $promo),
463 new UFC_Registered(true
),
464 new PFC_Not(new UFC_Dead())
466 if ($promoRegistered->getTotalCount() > 0.2 * $promoFull->getTotalCount()) {
467 $mymail = new PlMailer('admin/forums-promo.mail.tpl');
468 $mymail->assign('promo', $promo);
472 $registeredForums[] = $promoForum;
476 foreach ($registeredForums as $forum) {
477 XDB
::execute("INSERT INTO forum_subs (fid, uid)
484 // Update the global registration count stats.
485 $globals->updateNbIns();
488 // Update collateral data sources, and inform watchers by email.
491 // Email the referrer(s) of this new user.
492 $res = XDB
::iterRow("SELECT sender, GROUP_CONCAT(email SEPARATOR ', ') AS mails, MAX(last) AS lastDate
493 FROM register_marketing
496 ORDER BY lastDate DESC", $uid);
497 XDB
::execute("UPDATE register_mstats
499 WHERE uid = {?}", $uid);
502 while (list($senderid, $maketingEmails, $lastDate) = $res->next()) {
503 $sender = User
::getWithUID($senderid);
504 $market[] = " - par {$sender->fullName()} sur $maketingEmails (le plus récemment le $lastDate)";
505 $mymail = new PlMailer('register/marketer.mail.tpl');
506 $mymail->setSubject("$firstname $lastname s'est inscrit à Polytechnique.org !");
507 $mymail->setTo($sender);
508 $mymail->assign('sender', $sender);
509 $mymail->assign('firstname', $firstname);
510 $mymail->assign('lastname', $lastname);
511 $mymail->assign('promo', $promo);
512 $mymail->assign('sex', $sex);
513 $mymail->setTxtBody(wordwrap($msg, 72));
517 // Email the plat/al administrators about the registration.
518 if ($globals->register
->notif
) {
519 $mymail = new PlMailer('register/registration.mail.tpl');
520 $mymail->setSubject("Inscription de $firstname $lastname ($promo)");
521 $mymail->assign('firstname', $firstname);
522 $mymail->assign('lastname', $lastname);
523 $mymail->assign('promo', $promo);
524 $mymail->assign('sex', $sex);
525 $mymail->assign('birthdate', $birthdate);
526 $mymail->assign('birthdate_ref', $birthdate_ref);
527 $mymail->assign('forlife', $forlife);
528 $mymail->assign('email', $email);
529 $mymail->assign('logger', S
::logger());
530 if (count($market) > 0) {
531 $mymail->assign('market', implode("\n", $market));
533 $mymail->setTxtBody($msg);
537 // Remove old pending marketing requests for the new user.
538 Marketing
::clear($uid);
540 pl_redirect('profile/edit');
544 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: