Displays errors summary on registration alert emails (Closes #1506).
[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 $alert = array();
35 $alert_details = '';
36 $subState = new PlDict(S::v('subState', array()));
37 if (!$subState->has('step')) {
38 $subState->set('step', 0);
39 }
40 if (!$subState->has('backs')) {
41 $subState->set('backs', new PlDict());
42 }
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.";
50 }
51 }
52
53 if ($hash) {
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'",
66 $hash);
67
68 if ($res->numRows() == 1) {
69 $subState->merge($res->fetchOneRow());
70 $subState->set('main_mail_domain', User::$sub_mail_domains[$subState->v('type')]);
71
72 XDB::execute('INSERT INTO register_mstats (uid, sender, success)
73 SELECT m.uid, m.sender, 0
74 FROM register_marketing AS m
75 WHERE m.hash
76 ON DUPLICATE KEY UPDATE sender = VALUES(sender), success = VALUES(success)',
77 $subState->s('hash'));
78 }
79 }
80
81 switch ($subState->i('step')) {
82 case 0:
83 $wp = new PlWikiPage('Reference.Charte');
84 $wp->buildCache();
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);
91 }
92 }
93 break;
94
95 case 1:
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(*)
101 FROM accounts AS a
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 = {?}",
106 $yearpromo);
107
108 if (!$res->fetchOneCell()) {
109 $error = 'La promotion saisie est incorrecte ou tous les camarades de cette promotion sont inscrits !';
110 } else {
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);
124 }
125 }
126 }
127 }
128 break;
129
130 case 2:
131 if (count($_POST)) {
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'));
137 }
138 $error = checkNewUser($subState);
139
140 if ($error !== true) {
141 break;
142 }
143 $error = createAliases($subState);
144 if ($error === true) {
145 unset($error);
146 $subState->set('step', 3);
147 }
148 }
149 break;
150
151 case 3:
152 if (count($_POST)) {
153 $this->load('register.inc.php');
154
155 // Validate the email address format and domain.
156 require_once 'emails.inc.php';
157
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.';
163 }
164
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.";
169 } else {
170 $birth = explode('/', $birth, 3);
171 for ($i = 0; $i < 3; ++$i)
172 $birth[$i] = intval($birth[$i]);
173 if ($birth[2] < 100) {
174 $birth[2] += 1900;
175 }
176 $year = $birth[2];
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 : " . $birth . ' (date connue : ' . $subState->v('birthdateRef') . ')';
182 $subState->set('wrong_birthdate', $birth);
183 }
184 }
185
186 // Register the optional services requested by the user.
187 $services = array();
188 foreach (array('ax_letter', 'imap', 'ml_promo', 'nl') as $service) {
189 if (Post::b($service)) {
190 $services[] = $service;
191 }
192 }
193 $subState->set('services', $services);
194
195 // Validate the password.
196 if (!Post::v('pwhash', false)) {
197 $error[] = "Le mot de passe n'est pas valide.";
198 }
199
200 // Check if the given email is known as dangerous.
201 $res = XDB::query("SELECT state, description
202 FROM email_watch
203 WHERE email = {?} AND state != 'safe'",
204 Post::v('email'));
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') {
212 $bannedEmail = true;
213 }
214 }
215 if ($subState->i('watch') != 0) {
216 $alert[] = "Inscription d'un utilisateur surveillé";
217 $alert_details .= "\n * Commentaire pour la surveillance : " . $subState->v('comment');
218 }
219
220 if (($bannedIp = check_ip('unsafe'))) {
221 unset($error);
222 }
223
224 if (isset($error)) {
225 $error = join('<br />', $error);
226 } else {
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'));
231
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('birthdateRef') . ' (date connue : ' . $subState->s('birthdateRef') . ')';
238 }
239 if ($bannedIp) {
240 $alert[] = "Tentative d'inscription depuis une IP surveillée";
241 $alert_details .= "\n * IP surveillée : " . $_SESSION['check_ip'];
242 }
243
244 // Prevent banned user from actually registering; save the current state for others.
245 if ($bannedEmail || $bannedIp) {
246 global $globals;
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.";
251 } else {
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();
256 }
257 finishRegistration($subState);
258 }
259 }
260 }
261 break;
262 }
263
264 $_SESSION['subState'] = $subState->dict();
265 if (count($alert)) {
266 $alert_details = "Détails des alertes :" . $alert_details . "\n\n\n";
267 send_warning_mail(implode(' - ', $alert), $alert_details);
268 }
269
270 $page->changeTpl('register/step' . $subState->i('step') . '.tpl');
271 if (isset($error)) {
272 $page->trigError($error);
273 }
274 }
275
276 function handler_end($page, $hash = null)
277 {
278 global $globals;
279 $_SESSION['subState'] = array('step' => 5);
280
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);
287 return PL_FORBIDDEN;
288 }
289
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'",
304 $hash);
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&nbsp;:</p>
308 <ol>
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>
317 </ol>");
318 }
319
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;
324
325 // Prepare the template for display.
326 $page->changeTpl('register/end.tpl');
327 $page->assign('forlife', $forlife);
328 $page->assign('firstname', $firstname);
329
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)');
337 return;
338 }
339 } else {
340 return;
341 }
342
343 //
344 // Create the user account.
345 //
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
357 WHERE name = {?}',
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
362 WHERE name = {?}',
363 $bestalias, $uid, $mail_domain);
364 if ($emailXorg2) {
365 XDB::execute('INSERT INTO email_source_account (email, uid, type, flags, domain)
366 SELECT {?}, {?}, \'alias\', \'\', id
367 FROM email_virtual_domains
368 WHERE name = {?}',
369 $emailXorg2, $uid, $mail_domain);
370 }
371 XDB::commit();
372
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);
379
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);
383
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) {
387 switch ($service) {
388 case 'ax_letter':
389 NewsLetter::forGroup(NewsLetter::GROUP_AX)->subscribe($user);
390 break;
391 case 'nl':
392 NewsLetter::forGroup(NewsLetter::GROUP_XORG)->subscribe($user);
393 break;
394 case 'imap':
395 Email::activate_storage($user, 'imap', Bogo::IMAP_DEFAULT);
396 break;
397 case 'ml_promo':
398 if ($isX) {
399 $r = XDB::query('SELECT id FROM groups WHERE diminutif = {?}', $yearpromo);
400 if ($r->numRows()) {
401 $asso_id = $r->fetchOneCell();
402 XDB::execute('INSERT IGNORE INTO group_members (uid, asso_id)
403 VALUES ({?}, {?})',
404 $uid, $asso_id);
405 try {
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.");
411 }
412 }
413 }
414 break;
415 }
416 }
417
418 // Log the registration in the user session.
419 S::logger($uid)->log('inscription', $email);
420 XDB::execute("UPDATE register_pending
421 SET hash = 'INSCRIT'
422 WHERE uid = {?}", $uid);
423
424 // Congratulate our newly registered user by email.
425 $mymail = new PlMailer('register/success.mail.tpl');
426 $mymail->addTo("\"{$user->fullName()}\" <{$user->forlifeEmail()}>");
427 if ($isX) {
428 $mymail->setSubject('Bienvenue parmi les X sur le web !');
429 } else {
430 $mymail->setSubject('Bienvenue sur Polytechnique.org !');
431 }
432 $mymail->assign('forlife', $forlife);
433 $mymail->assign('firstname', $firstname);
434 $mymail->send();
435
436 // Index the user, to allow her to appear in searches.
437 Profile::rebuildSearchTokens($pid);
438
439 // Notify other users which were watching for her arrival.
440 XDB::execute('INSERT INTO contacts (uid, contact)
441 SELECT uid, ni_id
442 FROM watch_nonins
443 WHERE ni_id = {?}', $uid);
444 XDB::execute('DELETE FROM watch_nonins
445 WHERE ni_id = {?}', $uid);
446 Platal::session()->updateNbNotifs();
447
448 // Forcibly register the new user on default forums.
449 $registeredForums = array('xorg.general', 'xorg.pa.divers', 'xorg.pa.logements');
450
451 if ($isX) {
452 $promoForum = 'xorg.promo.' . strtolower($promo);
453 $exists = XDB::fetchOneCell('SELECT COUNT(*)
454 FROM forums
455 WHERE name = {?}',
456 $promoForum);
457
458 if ($exists == 0) {
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())
465 ));
466 if ($promoRegistered->getTotalCount() > 0.2 * $promoFull->getTotalCount()) {
467 $mymail = new PlMailer('admin/forums-promo.mail.tpl');
468 $mymail->assign('promo', $promo);
469 $mymail->send();
470 }
471 } else {
472 $registeredForums[] = $promoForum;
473 }
474 }
475
476 foreach ($registeredForums as $forum) {
477 XDB::execute("INSERT INTO forum_subs (fid, uid)
478 SELECT fid, {?}
479 FROM forums
480 WHERE name = {?}",
481 $uid, $val);
482 }
483
484 // Update the global registration count stats.
485 $globals->updateNbIns();
486
487 //
488 // Update collateral data sources, and inform watchers by email.
489 //
490
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
494 WHERE uid = {?}
495 GROUP BY sender
496 ORDER BY lastDate DESC", $uid);
497 XDB::execute("UPDATE register_mstats
498 SET success = NOW()
499 WHERE uid = {?}", $uid);
500
501 $market = array();
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));
514 $mymail->send();
515 }
516
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));
532 }
533 $mymail->setTxtBody($msg);
534 $mymail->send();
535 }
536
537 // Remove old pending marketing requests for the new user.
538 Marketing::clear($uid);
539
540 pl_redirect('profile/edit');
541 }
542 }
543
544 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
545 ?>