Enables @polytechnique.edu adresses for old promotions (Closes #1516)
[platal.git] / modules / register.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2011 Polytechnique.org *
4 * http://opensource.polytechnique.org/ *
5 * *
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. *
10 * *
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. *
15 * *
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 *
18 * Foundation, Inc., *
19 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
20 ***************************************************************************/
21
22 class RegisterModule extends PLModule
23 {
24 function handlers()
25 {
26 return array(
27 'register' => $this->make_hook('register', AUTH_PUBLIC),
28 'register/end' => $this->make_hook('end', AUTH_PUBLIC),
29 );
30 }
31
32 function handler_register($page, $hash = null)
33 {
34 $page->forceSkin('register');
35
36 $alert = array();
37 $alert_details = '';
38 $subState = new PlDict(S::v('subState', array()));
39 if (!$subState->has('step')) {
40 $subState->set('step', 0);
41 }
42 if (!$subState->has('backs')) {
43 $subState->set('backs', new PlDict());
44 }
45 if (Get::has('back') && Get::i('back') < $subState->i('step')) {
46 $subState->set('step', max(0, Get::i('back')));
47 $subState->v('backs')->set($subState->v('backs')->count() + 1, $subState->dict());
48 $subState->v('backs')->kill('backs');
49 if ($subState->v('backs')->count() == 3) {
50 $alert[] = "Tentative d'inscription très hésitante";
51 $alert_details .= "\n * Retours en arrières : 3.";
52 }
53 }
54
55 if ($hash) {
56 $res = XDB::query("SELECT a.uid, a.hruid, ppn.lastname_initial AS lastname, ppn.firstname_initial AS firstname, p.xorg_id AS xorgid,
57 pd.promo, pe.promo_year AS yearpromo, pde.degree AS edu_type,
58 p.birthdate_ref AS birthdateRef, FIND_IN_SET('watch', a.flags) AS watch, m.hash, a.type, a.comment
59 FROM register_marketing AS m
60 INNER JOIN accounts AS a ON (m.uid = a.uid)
61 INNER JOIN account_profiles AS ap ON (a.uid = ap.uid AND FIND_IN_SET('owner', ap.perms))
62 INNER JOIN profiles AS p ON (p.pid = ap.pid)
63 INNER JOIN profile_display AS pd ON (p.pid = pd.pid)
64 INNER JOIN profile_education AS pe ON (pe.pid = p.pid AND FIND_IN_SET('primary', pe.flags))
65 INNER JOIN profile_education_degree_enum AS pde ON (pde.id = pe.degreeid)
66 INNER JOIN profile_public_names AS ppn ON (ppn.pid = p.pid)
67 WHERE m.hash = {?} AND a.state = 'pending'",
68 $hash);
69
70 if ($res->numRows() == 1) {
71 $subState->merge($res->fetchOneRow());
72 $subState->set('main_mail_domain', User::$sub_mail_domains[$subState->v('type')]);
73
74 XDB::execute('INSERT INTO register_mstats (uid, sender, success)
75 SELECT m.uid, m.sender, 0
76 FROM register_marketing AS m
77 WHERE m.hash
78 ON DUPLICATE KEY UPDATE sender = VALUES(sender), success = VALUES(success)',
79 $subState->s('hash'));
80 }
81 }
82
83 switch ($subState->i('step')) {
84 case 0:
85 $wp = new PlWikiPage('Reference.Charte');
86 $wp->buildCache();
87 if (Post::has('step1')) {
88 $subState->set('step', 1);
89 if ($subState->has('hash')) {
90 $subState->set('step', 3);
91 $this->load('register.inc.php');
92 createAliases($subState);
93 }
94 }
95 break;
96
97 case 1:
98 if (Post::has('yearpromo')) {
99 $edu_type = Post::t('edu_type');
100 $yearpromo = Post::i('yearpromo');
101 $promo = Profile::$cycle_prefixes[$edu_type] . $yearpromo;
102 $res = XDB::query("SELECT COUNT(*)
103 FROM accounts AS a
104 INNER JOIN account_profiles AS ap ON (a.uid = ap.uid AND FIND_IN_SET('owner', ap.perms))
105 INNER JOIN profiles AS p ON (p.pid = ap.pid)
106 INNER JOIN profile_education AS pe ON (pe.pid = p.pid AND FIND_IN_SET('primary', pe.flags))
107 WHERE a.state = 'pending' AND p.deathdate IS NULL AND pe.promo_year = {?}",
108 $yearpromo);
109
110 if (!$res->fetchOneCell()) {
111 $error = 'La promotion saisie est incorrecte ou tous les camarades de cette promotion sont inscrits !';
112 } else {
113 $subState->set('step', 2);
114 $subState->set('promo', $promo);
115 $subState->set('yearpromo', $yearpromo);
116 $subState->set('edu_type', $edu_type);
117 if ($edu_type == Profile::DEGREE_X) {
118 if ($yearpromo >= 1996 && $yearpromo < 2000) {
119 $subState->set('schoolid', ($yearpromo % 100) * 10 . '???');
120 $subState->set('schoolid_exemple', ($yearpromo % 100) * 10000 + 532);
121 $subState->set('schoolid_exemple_ev2', (($yearpromo + 1) % 100) * 10000 + 532);
122 } elseif($yearpromo >= 2000) {
123 $subState->set('schoolid', 100 + ($yearpromo % 100) . '???');
124 $subState->set('schoolid_exemple', (100 + ($yearpromo % 100)) * 1000 + 532);
125 $subState->set('schoolid_exemple_ev2', (100 + (($yearpromo + 1) % 100)) * 1000 + 532);
126 }
127 }
128 }
129 }
130 break;
131
132 case 2:
133 if (count($_POST)) {
134 $this->load('register.inc.php');
135 $subState->set('firstname', Post::t('firstname'));
136 $subState->set('lastname', Post::t('lastname'));
137 if (Post::has('schoolid')) {
138 $subState->set('schoolid', Post::i('schoolid'));
139 }
140 $error = checkNewUser($subState);
141
142 if ($error !== true) {
143 break;
144 }
145 $error = createAliases($subState);
146 if ($error === true) {
147 unset($error);
148 $subState->set('step', 3);
149 }
150 }
151 break;
152
153 case 3:
154 if (count($_POST)) {
155 $this->load('register.inc.php');
156
157 // Validate the email address format and domain.
158 require_once 'emails.inc.php';
159
160 $user = User::get($subState->s('uid'));
161 if (!isvalid_email(Post::v('email'))) {
162 $error[] = "Le champ 'Email' n'est pas valide.";
163 } elseif (!isvalid_email_redirection(Post::v('email'), $user)) {
164 $error[] = $subState->s('forlife') . ' doit renvoyer vers un email existant '
165 . 'valide, en particulier, il ne peut pas être renvoyé vers lui-même.';
166 }
167
168 // Validate the birthday format and range.
169 $birth = Post::t('birthdate');
170 if (!preg_match('@^[0-3]?\d/[01]?\d/(19|20)?\d{2}$@', $birth)) {
171 $error[] = "La 'Date de naissance' n'est pas correcte.";
172 } else {
173 $birth = explode('/', $birth, 3);
174 for ($i = 0; $i < 3; ++$i)
175 $birth[$i] = intval($birth[$i]);
176 if ($birth[2] < 100) {
177 $birth[2] += 1900;
178 }
179 $year = $birth[2];
180 $ref_year = substr($subState->v('birthdateRef'), 0, 4);
181 if (abs($ref_year - $year) > 2) {
182 $error[] = "La 'Date de naissance' n'est pas correcte.";
183 $alert[] = "Date de naissance incorrecte à l'inscription";
184 $alert_details .= "\n * Date de naissance renseignée : " . Post::t('birthdate') . ' (date connue : ' . $subState->v('birthdateRef') . ')';
185 $subState->set('wrong_birthdate', $birth);
186 }
187 }
188
189 // Register the optional services requested by the user.
190 $services = array();
191 foreach (array('ax_letter', 'imap', 'ml_promo', 'nl') as $service) {
192 if (Post::b($service)) {
193 $services[] = $service;
194 }
195 }
196 $subState->set('services', $services);
197
198 // Validate the password.
199 if (!Post::v('pwhash', false)) {
200 $error[] = "Le mot de passe n'est pas valide.";
201 }
202
203 // Check if the given email is known as dangerous.
204 $res = XDB::query("SELECT state, description
205 FROM email_watch
206 WHERE email = {?} AND state != 'safe'",
207 Post::v('email'));
208 $bannedEmail = false;
209 if ($res->numRows()) {
210 list($state, $description) = $res->fetchOneRow();
211 $alert[] = "Email surveillé proposé à l'inscription";
212 $alert_details .= "\n * Email surveillé : " . Post::v('email');
213 $subState->set('email_desc', $description);
214 if ($state == 'dangerous') {
215 $bannedEmail = true;
216 }
217 }
218 if ($subState->i('watch') != 0) {
219 $alert[] = "Inscription d'un utilisateur surveillé";
220 $alert_details .= "\n * Commentaire pour la surveillance : " . $subState->v('comment');
221 }
222
223 if (($bannedIp = check_ip('unsafe'))) {
224 unset($error);
225 }
226
227 if (isset($error)) {
228 $error = join('<br />', $error);
229 } else {
230 $subState->set('birthdate', sprintf("%04d-%02d-%02d",
231 intval($birth[2]), intval($birth[1]), intval($birth[0])));
232 $subState->set('email', Post::t('email'));
233 $subState->set('password', Post::t('pwhash'));
234
235 // Update the current alert if the birthdate is incorrect,
236 // or if the IP address of the user has been banned.
237 if ($subState->s('birthdateRef') != '0000-00-00'
238 && $subState->s('birthdateRef') != $subState->s('birthdate')) {
239 $alert[] = "Date de naissance incorrecte à l'inscription";
240 $alert_details .= "\n * Date de naissance renseignée : " . $subState->s('birthdate') . ' (date connue : ' . $subState->s('birthdateRef') . ')';
241 }
242 if ($bannedIp) {
243 $alert[] = "Tentative d'inscription depuis une IP surveillée";
244 $alert_details .= "\n * IP surveillée : " . $_SESSION['check_ip'];
245 }
246
247 // Prevent banned user from actually registering; save the current state for others.
248 if ($bannedEmail || $bannedIp) {
249 global $globals;
250 $error = "Une erreur s'est produite lors de l'inscription."
251 . " Merci de contacter <a href='mailto:register@{$globals->mail->domain}>"
252 . " register@{$globals->mail->domain}</a>"
253 . " pour nous faire part de cette erreur.";
254 } else {
255 $subState->set('step', 4);
256 if ($subState->v('backs')->count() >= 3) {
257 $alert[] = "Fin d'une inscription hésitante";
258 $alert_details .= "\n * Nombre de retours en arrière : " . $subState->v('backs')->count();
259 }
260 finishRegistration($subState);
261 }
262 }
263 }
264 break;
265 }
266
267 $_SESSION['subState'] = $subState->dict();
268 if (count($alert)) {
269 $alert_details = "Détails des alertes :" . $alert_details . "\n\n\n";
270 send_warning_mail(implode(' - ', $alert), $alert_details);
271 }
272
273 $page->changeTpl('register/step' . $subState->i('step') . '.tpl');
274 if (isset($error)) {
275 $page->trigError($error);
276 }
277 }
278
279 function handler_end($page, $hash = null)
280 {
281 global $globals;
282 $_SESSION['subState'] = array('step' => 5);
283
284 // Reject registration requests from unsafe IP addresses (and remove the
285 // registration information from the database, to prevent IP changes).
286 if (check_ip('unsafe')) {
287 send_warning_mail('Une IP surveillée a tenté de finaliser son inscription.');
288 XDB::execute("DELETE FROM register_pending
289 WHERE hash = {?} AND hash != 'INSCRIT'", $hash);
290 return PL_FORBIDDEN;
291 }
292
293 // Retrieve the pre-registration information using the url-provided
294 // authentication token.
295 $res = XDB::query("SELECT r.uid, p.pid, r.forlife, r.bestalias, r.mailorg2,
296 r.password, r.email, r.services, r.naissance,
297 ppn.lastname_initial, ppn.firstname_initial, pe.promo_year,
298 pd.promo, p.sex, p.birthdate_ref, a.type
299 FROM register_pending AS r
300 INNER JOIN accounts AS a ON (r.uid = a.uid)
301 INNER JOIN account_profiles AS ap ON (a.uid = ap.uid AND FIND_IN_SET('owner', ap.perms))
302 INNER JOIN profiles AS p ON (p.pid = ap.pid)
303 INNER JOIN profile_public_names AS ppn ON (ppn.pid = p.pid)
304 INNER JOIN profile_display AS pd ON (p.pid = pd.pid)
305 INNER JOIN profile_education AS pe ON (pe.pid = p.pid AND FIND_IN_SET('primary', pe.flags))
306 WHERE hash = {?} AND hash != 'INSCRIT' AND a.state = 'pending'",
307 $hash);
308 if (!$hash || $res->numRows() == 0) {
309 $page->kill("<p>Cette adresse n'existe pas, ou plus, sur le serveur.</p>
310 <p>Causes probables&nbsp;:</p>
311 <ol>
312 <li>Vérifie que tu visites l'adresse du dernier
313 email reçu s'il y en a eu plusieurs.</li>
314 <li>Tu as peut-être mal copié l'adresse reçue par
315 email, vérifie-la à la main.</li>
316 <li>Tu as peut-être attendu trop longtemps pour
317 confirmer. Les pré-inscriptions sont annulées
318 tous les 30 jours.</li>
319 <li>Tu es en fait déjà inscrit.</li>
320 </ol>");
321 }
322
323 list($uid, $pid, $forlife, $bestalias, $emailXorg2, $password, $email, $services,
324 $birthdate, $lastname, $firstname, $yearpromo, $promo, $sex, $birthdate_ref, $type) = $res->fetchOneRow();
325 $isX = ($type == 'x');
326 $mail_domain = User::$sub_mail_domains[$type] . $globals->mail->domain;
327
328 // Prepare the template for display.
329 $page->changeTpl('register/end.tpl');
330 $page->assign('forlife', $forlife);
331 $page->assign('firstname', $firstname);
332
333 // Check if the user did enter a valid password; if not (or if none is found),
334 // get her an information page.
335 if (Post::has('response')) {
336 $expected_response = sha1("$forlife:$password:" . S::v('challenge'));
337 if (Post::v('response') != $expected_response) {
338 $page->trigError("Mot de passe invalide.");
339 S::logger($uid)->log('auth_fail', 'bad password (register/end)');
340 return;
341 }
342 } else {
343 return;
344 }
345
346 //
347 // Create the user account.
348 //
349 XDB::startTransaction();
350 XDB::execute("UPDATE accounts
351 SET password = {?}, state = 'active',
352 registration_date = NOW(), email = NULL
353 WHERE uid = {?}", $password, $uid);
354 XDB::execute("UPDATE profiles
355 SET birthdate = {?}, last_change = NOW()
356 WHERE pid = {?}", $birthdate, $pid);
357 XDB::execute('INSERT INTO email_source_account (email, uid, type, flags, domain)
358 SELECT {?}, {?}, \'forlife\', \'\', id
359 FROM email_virtual_domains
360 WHERE name = {?}',
361 $forlife, $uid, $mail_domain);
362 XDB::execute('INSERT INTO email_source_account (email, uid, type, flags, domain)
363 SELECT {?}, {?}, \'alias\', \'bestalias\', id
364 FROM email_virtual_domains
365 WHERE name = {?}',
366 $bestalias, $uid, $mail_domain);
367 if ($emailXorg2) {
368 XDB::execute('INSERT INTO email_source_account (email, uid, type, flags, domain)
369 SELECT {?}, {?}, \'alias\', \'\', id
370 FROM email_virtual_domains
371 WHERE name = {?}',
372 $emailXorg2, $uid, $mail_domain);
373 }
374 XDB::commit();
375
376 // Add the registration email address as first and only redirection.
377 require_once 'emails.inc.php';
378 $user = User::getSilentWithUID($uid);
379 $redirect = new Redirect($user);
380 $redirect->add_email($email);
381 fix_bestalias($user);
382
383 // Try to start a session (so the user don't have to log in); we will use
384 // the password available in Post:: to authenticate the user.
385 Platal::session()->start(AUTH_PASSWD);
386
387 // Subscribe the user to the services she did request at registration time.
388 require_once 'newsletter.inc.php';
389 foreach (explode(',', $services) as $service) {
390 switch ($service) {
391 case 'ax_letter':
392 NewsLetter::forGroup(NewsLetter::GROUP_AX)->subscribe($user);
393 break;
394 case 'nl':
395 NewsLetter::forGroup(NewsLetter::GROUP_XORG)->subscribe($user);
396 break;
397 case 'imap':
398 Email::activate_storage($user, 'imap', Bogo::IMAP_DEFAULT);
399 break;
400 case 'ml_promo':
401 if ($isX) {
402 $r = XDB::query('SELECT id FROM groups WHERE diminutif = {?}', $yearpromo);
403 if ($r->numRows()) {
404 $asso_id = $r->fetchOneCell();
405 XDB::execute('INSERT IGNORE INTO group_members (uid, asso_id)
406 VALUES ({?}, {?})',
407 $uid, $asso_id);
408 try {
409 $mmlist = new MMList($user);
410 $mmlist->subscribe("promo" . $yearpromo);
411 } catch (Exception $e) {
412 PlErrorReport::report($e);
413 $page->trigError("L'inscription à la liste promo" . $yearpromo . " a échouée.");
414 }
415 }
416 }
417 break;
418 }
419 }
420
421 // Log the registration in the user session.
422 S::logger($uid)->log('inscription', $email);
423 XDB::execute("UPDATE register_pending
424 SET hash = 'INSCRIT'
425 WHERE uid = {?}", $uid);
426
427 // Congratulate our newly registered user by email.
428 $mymail = new PlMailer('register/success.mail.tpl');
429 $mymail->addTo("\"{$user->fullName()}\" <{$user->forlifeEmail()}>");
430 if ($isX) {
431 $mymail->setSubject('Bienvenue parmi les X sur le web !');
432 } else {
433 $mymail->setSubject('Bienvenue sur Polytechnique.org !');
434 }
435 $mymail->assign('forlife', $forlife);
436 $mymail->assign('firstname', $firstname);
437 $mymail->send();
438
439 // Index the user, to allow her to appear in searches.
440 Profile::rebuildSearchTokens($pid);
441
442 // Notify other users which were watching for her arrival.
443 XDB::execute('INSERT INTO contacts (uid, contact)
444 SELECT uid, ni_id
445 FROM watch_nonins
446 WHERE ni_id = {?}', $uid);
447 XDB::execute('DELETE FROM watch_nonins
448 WHERE ni_id = {?}', $uid);
449 Platal::session()->updateNbNotifs();
450
451 // Forcibly register the new user on default forums.
452 $registeredForums = array('xorg.general', 'xorg.pa.divers', 'xorg.pa.logements');
453
454 if ($isX) {
455 $promoForum = 'xorg.promo.' . strtolower($promo);
456 $exists = XDB::fetchOneCell('SELECT COUNT(*)
457 FROM forums
458 WHERE name = {?}',
459 $promoForum);
460
461 if ($exists == 0) {
462 // Notify the newsgroup admin of the promotion forum needs be created.
463 $promoFull = new UserFilter(new UFC_Promo('=', UserFilter::DISPLAY, $promo));
464 $promoRegistered = new UserFilter(new PFC_And(
465 new UFC_Promo('=', UserFilter::DISPLAY, $promo),
466 new UFC_Registered(true),
467 new PFC_Not(new UFC_Dead())
468 ));
469 if ($promoRegistered->getTotalCount() > 0.2 * $promoFull->getTotalCount()) {
470 $mymail = new PlMailer('admin/forums-promo.mail.tpl');
471 $mymail->assign('promo', $promo);
472 $mymail->send();
473 }
474 } else {
475 $registeredForums[] = $promoForum;
476 }
477 }
478
479 foreach ($registeredForums as $forum) {
480 XDB::execute("INSERT INTO forum_subs (fid, uid)
481 SELECT fid, {?}
482 FROM forums
483 WHERE name = {?}",
484 $uid, $val);
485 }
486
487 // Update the global registration count stats.
488 $globals->updateNbIns();
489
490 //
491 // Update collateral data sources, and inform watchers by email.
492 //
493
494 // Email the referrer(s) of this new user.
495 $res = XDB::iterRow("SELECT sender, GROUP_CONCAT(email SEPARATOR ', ') AS mails, MAX(last) AS lastDate
496 FROM register_marketing
497 WHERE uid = {?}
498 GROUP BY sender
499 ORDER BY lastDate DESC", $uid);
500 XDB::execute("UPDATE register_mstats
501 SET success = NOW()
502 WHERE uid = {?}", $uid);
503
504 $market = array();
505 while (list($senderid, $maketingEmails, $lastDate) = $res->next()) {
506 $sender = User::getWithUID($senderid);
507 $market[] = " - par {$sender->fullName()} sur $maketingEmails (le plus récemment le $lastDate)";
508 $mymail = new PlMailer('register/marketer.mail.tpl');
509 $mymail->setSubject("$firstname $lastname s'est inscrit à Polytechnique.org !");
510 $mymail->setTo($sender);
511 $mymail->assign('sender', $sender);
512 $mymail->assign('firstname', $firstname);
513 $mymail->assign('lastname', $lastname);
514 $mymail->assign('promo', $promo);
515 $mymail->assign('sex', $sex);
516 $mymail->setTxtBody(wordwrap($msg, 72));
517 $mymail->send();
518 }
519
520 // Email the plat/al administrators about the registration.
521 if ($globals->register->notif) {
522 $mymail = new PlMailer('register/registration.mail.tpl');
523 $mymail->setSubject("Inscription de $firstname $lastname ($promo)");
524 $mymail->assign('firstname', $firstname);
525 $mymail->assign('lastname', $lastname);
526 $mymail->assign('promo', $promo);
527 $mymail->assign('sex', $sex);
528 $mymail->assign('birthdate', $birthdate);
529 $mymail->assign('birthdate_ref', $birthdate_ref);
530 $mymail->assign('forlife', $forlife);
531 $mymail->assign('email', $email);
532 $mymail->assign('logger', S::logger());
533 if (count($market) > 0) {
534 $mymail->assign('market', implode("\n", $market));
535 }
536 $mymail->setTxtBody($msg);
537 $mymail->send();
538 }
539
540 // Remove old pending marketing requests for the new user.
541 Marketing::clear($uid);
542
543 pl_redirect('profile/edit');
544 }
545 }
546
547 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
548 ?>