Moving to GitHub.
[platal.git] / modules / register.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2014 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');
185 if ($subState->v('birthdateRef') == '0000-00-00') {
186 $alert_details .= ' (date inconnue)';
187 } else {
188 $alert_details .= ' (date connue : ' . $subState->v('birthdateRef') . ')';
189 }
190 $subState->set('wrong_birthdate', $birth);
191 }
192 }
193
194 // Register the optional services requested by the user.
195 $services = array();
196 foreach (array('com_letters', 'imap', 'ml_promo', 'nl') as $service) {
197 if (Post::b($service)) {
198 $services[] = $service;
199 }
200 }
201 $subState->set('services', $services);
202
203 // Validate the password.
204 if (!Post::v('pwhash', false)) {
205 $error[] = "Le mot de passe n'est pas valide.";
206 }
207
208 // Check if the given email is known as dangerous.
209 $res = XDB::query("SELECT state, description
210 FROM email_watch
211 WHERE email = {?} AND state != 'safe'",
212 Post::v('email'));
213 $bannedEmail = false;
214 if ($res->numRows()) {
215 list($state, $description) = $res->fetchOneRow();
216 $alert[] = "Email surveillé proposé à l'inscription";
217 $alert_details .= "\n * Email surveillé : " . Post::v('email');
218 $subState->set('email_desc', $description);
219 if ($state == 'dangerous') {
220 $bannedEmail = true;
221 }
222 }
223 if ($subState->i('watch') != 0) {
224 $alert[] = "Inscription d'un utilisateur surveillé";
225 $alert_details .= "\n * Commentaire pour la surveillance : " . $subState->v('comment');
226 }
227
228 if (($bannedIp = check_ip('unsafe'))) {
229 unset($error);
230 }
231
232 if (isset($error)) {
233 $error = join('<br />', $error);
234 } else {
235 $subState->set('birthdate', sprintf("%04d-%02d-%02d",
236 intval($birth[2]), intval($birth[1]), intval($birth[0])));
237 $subState->set('email', Post::t('email'));
238 $subState->set('password', Post::t('pwhash'));
239
240 // Update the current alert if the birthdate is incorrect,
241 // or if the IP address of the user has been banned.
242 if ($subState->s('birthdateRef') != '0000-00-00'
243 && $subState->s('birthdateRef') != $subState->s('birthdate')) {
244 $alert[] = "Date de naissance incorrecte à l'inscription";
245 $alert_details .= "\n * Date de naissance renseignée : " . Post::t('birthdate');
246 if ($subState->v('birthdateRef') == '0000-00-00') {
247 $alert_details .= ' (date inconnue)';
248 } else {
249 $alert_details .= ' (date connue : ' . $subState->v('birthdateRef') . ')';
250 }
251 }
252 if ($bannedIp) {
253 $alert[] = "Tentative d'inscription depuis une IP surveillée";
254 $alert_details .= "\n * IP surveillée : " . $_SESSION['check_ip'];
255 }
256
257 // Prevent banned user from actually registering; save the current state for others.
258 if ($bannedEmail || $bannedIp) {
259 global $globals;
260 $error = "Une erreur s'est produite lors de l'inscription."
261 . " Merci de contacter <a href='mailto:register@{$globals->mail->domain}>"
262 . " register@{$globals->mail->domain}</a>"
263 . " pour nous faire part de cette erreur.";
264 } else {
265 $subState->set('step', 4);
266 if ($subState->v('backs')->count() >= 3) {
267 $alert[] = "Fin d'une inscription hésitante";
268 $alert_details .= "\n * Nombre de retours en arrière : " . $subState->v('backs')->count();
269 }
270 finishRegistration($subState);
271 }
272 }
273 }
274 break;
275 }
276
277 $_SESSION['subState'] = $subState->dict();
278 if (count($alert)) {
279 $alert_details = "Détails des alertes :" . $alert_details . "\n\n";
280 $alert_details .= 'Compte concerné : ' . $subState->s('forlife') . ' (redirection vers : '
281 . ($subState->s('email') == '' ? Post::t('email') : $subState->s('email')). ")\n\n\n";
282 send_warning_mail(implode(' - ', $alert), $alert_details);
283 }
284
285 $page->changeTpl('register/step' . $subState->i('step') . '.tpl');
286 if (isset($error)) {
287 $page->trigError($error);
288 }
289 }
290
291 function handler_end($page, $hash = null)
292 {
293 global $globals;
294 $_SESSION['subState'] = array('step' => 5);
295
296 // Reject registration requests from unsafe IP addresses (and remove the
297 // registration information from the database, to prevent IP changes).
298 if (check_ip('unsafe')) {
299 send_warning_mail('Une IP surveillée a tenté de finaliser son inscription.');
300 XDB::execute("DELETE FROM register_pending
301 WHERE hash = {?} AND hash != 'INSCRIT'", $hash);
302 return PL_FORBIDDEN;
303 }
304
305 // Retrieve the pre-registration information using the url-provided
306 // authentication token.
307 $res = XDB::query("SELECT r.uid, p.pid, r.forlife, r.bestalias, r.mailorg2,
308 r.password, r.email, r.services, r.naissance,
309 ppn.lastname_initial, ppn.firstname_initial, pe.promo_year,
310 pd.promo, p.sex, p.birthdate_ref, a.type, a.email AS old_account_email
311 FROM register_pending AS r
312 INNER JOIN accounts AS a ON (r.uid = a.uid)
313 INNER JOIN account_profiles AS ap ON (a.uid = ap.uid AND FIND_IN_SET('owner', ap.perms))
314 INNER JOIN profiles AS p ON (p.pid = ap.pid)
315 INNER JOIN profile_public_names AS ppn ON (ppn.pid = p.pid)
316 INNER JOIN profile_display AS pd ON (p.pid = pd.pid)
317 INNER JOIN profile_education AS pe ON (pe.pid = p.pid AND FIND_IN_SET('primary', pe.flags))
318 WHERE hash = {?} AND hash != 'INSCRIT' AND a.state = 'pending'",
319 $hash);
320 if (!$hash || $res->numRows() == 0) {
321 $page->kill("<p>Cette adresse n'existe pas, ou plus, sur le serveur.</p>
322 <p>Causes probables&nbsp;:</p>
323 <ol>
324 <li>Vérifie que tu visites l'adresse du dernier
325 email reçu s'il y en a eu plusieurs.</li>
326 <li>Tu as peut-être mal copié l'adresse reçue par
327 email, vérifie-la à la main.</li>
328 <li>Tu as peut-être attendu trop longtemps pour
329 confirmer. Les pré-inscriptions sont annulées
330 tous les 30 jours.</li>
331 <li>Tu es en fait déjà inscrit.</li>
332 </ol>");
333 }
334
335 list($uid, $pid, $forlife, $bestalias, $emailXorg2, $password, $email, $services,
336 $birthdate, $lastname, $firstname, $yearpromo, $promo, $sex, $birthdate_ref, $type, $old_account_email) = $res->fetchOneRow();
337 $isX = ($type == 'x');
338 $mail_domain = User::$sub_mail_domains[$type] . $globals->mail->domain;
339
340 // Prepare the template for display.
341 $page->changeTpl('register/end.tpl');
342 $page->assign('forlife', $forlife);
343 $page->assign('firstname', $firstname);
344
345 // Check if the user did enter a valid password; if not (or if none is found),
346 // get her an information page.
347 if (Post::has('response')) {
348 $expected_response = sha1("$forlife:$password:" . S::v('challenge'));
349 if (Post::v('response') != $expected_response) {
350 $page->trigError("Mot de passe invalide.");
351 S::logger($uid)->log('auth_fail', 'bad password (register/end)');
352 return;
353 }
354 } else {
355 return;
356 }
357
358 //
359 // Create the user account.
360 //
361 XDB::startTransaction();
362 XDB::execute("UPDATE accounts
363 SET password = {?}, state = 'active',
364 registration_date = NOW(), email = NULL
365 WHERE uid = {?}", $password, $uid);
366 XDB::execute("UPDATE profiles
367 SET birthdate = {?}, last_change = NOW()
368 WHERE pid = {?}", $birthdate, $pid);
369 XDB::execute('INSERT INTO email_source_account (email, uid, type, flags, domain)
370 SELECT {?}, {?}, \'forlife\', \'\', id
371 FROM email_virtual_domains
372 WHERE name = {?}',
373 $forlife, $uid, $mail_domain);
374 XDB::execute('INSERT INTO email_source_account (email, uid, type, flags, domain)
375 SELECT {?}, {?}, \'alias\', \'bestalias\', id
376 FROM email_virtual_domains
377 WHERE name = {?}',
378 $bestalias, $uid, $mail_domain);
379 if ($emailXorg2) {
380 XDB::execute('INSERT INTO email_source_account (email, uid, type, flags, domain)
381 SELECT {?}, {?}, \'alias\', \'\', id
382 FROM email_virtual_domains
383 WHERE name = {?}',
384 $emailXorg2, $uid, $mail_domain);
385 }
386 XDB::commit();
387
388 // Try to start a session (so the user don't have to log in); we will use
389 // the password available in Post:: to authenticate the user.
390 Platal::session()->start(AUTH_PASSWD);
391
392 // Add the registration email address as first and only redirection.
393 require_once 'emails.inc.php';
394 $user = User::getSilentWithUID($uid);
395 $redirect = new Redirect($user);
396 $redirect->add_email($email);
397 fix_bestalias($user);
398
399 // If the user was registered to some aliases and MLs, we must change
400 // the subscription to her forlife email.
401 if ($old_account_email) {
402 $listClient = new MMList($user);
403 $listClient->change_user_email($old_account_email, $user->forlifeEmail());
404 update_alias_user($old_account_email, $user->forlifeEmail());
405 }
406
407 // Subscribe the user to the services she did request at registration time.
408 require_once 'newsletter.inc.php';
409 foreach (explode(',', $services) as $service) {
410 switch ($service) {
411 case 'ax_letter': /* This option is deprecated by 'com_letters' */
412 NewsLetter::forGroup(NewsLetter::GROUP_AX)->subscribe($user);
413 break;
414 case 'com_letters':
415 NewsLetter::forGroup(NewsLetter::GROUP_AX)->subscribe($user);
416 NewsLetter::forGroup(NewsLetter::GROUP_EP)->subscribe($user);
417 NewsLetter::forGroup(NewsLetter::GROUP_FX)->subscribe($user);
418 break;
419 case 'nl':
420 NewsLetter::forGroup(NewsLetter::GROUP_XORG)->subscribe($user);
421 break;
422 case 'imap':
423 Email::activate_storage($user, 'imap', Bogo::IMAP_DEFAULT);
424 break;
425 case 'ml_promo':
426 if ($isX) {
427 $r = XDB::query('SELECT id FROM groups WHERE diminutif = {?}', $yearpromo);
428 if ($r->numRows()) {
429 $asso_id = $r->fetchOneCell();
430 XDB::execute('INSERT IGNORE INTO group_members (uid, asso_id)
431 VALUES ({?}, {?})',
432 $uid, $asso_id);
433 try {
434 MailingList::subscribePromo($yearpromo, $user);
435 } catch (Exception $e) {
436 PlErrorReport::report($e);
437 $page->trigError("L'inscription à la liste promo" . $yearpromo . " a échouée.");
438 }
439 }
440 }
441 break;
442 }
443 }
444
445 // Log the registration in the user session.
446 S::logger($uid)->log('inscription', $email);
447 XDB::execute("UPDATE register_pending
448 SET hash = 'INSCRIT'
449 WHERE uid = {?}", $uid);
450
451 // Congratulate our newly registered user by email.
452 $mymail = new PlMailer('register/success.mail.tpl');
453 $mymail->addTo("\"{$user->fullName()}\" <{$user->forlifeEmail()}>");
454 if ($isX) {
455 $mymail->setSubject('Bienvenue parmi les X sur le web !');
456 } else {
457 $mymail->setSubject('Bienvenue sur Polytechnique.org !');
458 }
459 $mymail->assign('forlife', $forlife);
460 $mymail->assign('firstname', $firstname);
461 $mymail->send();
462
463 // Index the user, to allow her to appear in searches.
464 Profile::rebuildSearchTokens($pid);
465
466 // Notify other users which were watching for her arrival.
467 XDB::execute('INSERT INTO contacts (uid, contact)
468 SELECT uid, {?}
469 FROM watch_nonins
470 WHERE ni_id = {?}', $pid, $uid);
471 XDB::execute('DELETE FROM watch_nonins
472 WHERE ni_id = {?}', $uid);
473 Platal::session()->updateNbNotifs();
474
475 // Forcibly register the new user on default forums.
476 $registeredForums = array('xorg.general', 'xorg.pa.divers', 'xorg.pa.logements');
477
478 if ($isX) {
479 $promoForum = 'xorg.promo.' . strtolower($promo);
480 $exists = XDB::fetchOneCell('SELECT COUNT(*)
481 FROM forums
482 WHERE name = {?}',
483 $promoForum);
484
485 if ($exists == 0) {
486 // Notify the newsgroup admin of the promotion forum needs be created.
487 $promoFull = new UserFilter(new UFC_Promo('=', UserFilter::DISPLAY, $promo));
488 $promoRegistered = new UserFilter(new PFC_And(
489 new UFC_Promo('=', UserFilter::DISPLAY, $promo),
490 new UFC_Registered(true),
491 new PFC_Not(new UFC_Dead())
492 ));
493 if ($promoRegistered->getTotalCount() > 0.2 * $promoFull->getTotalCount()) {
494 $mymail = new PlMailer('admin/forums-promo.mail.tpl');
495 $mymail->assign('promo', $promo);
496 $mymail->send();
497 }
498 } else {
499 $registeredForums[] = $promoForum;
500 }
501 }
502
503 foreach ($registeredForums as $forum) {
504 XDB::execute("INSERT INTO forum_subs (fid, uid)
505 SELECT fid, {?}
506 FROM forums
507 WHERE name = {?}",
508 $uid, $val);
509 }
510
511 // Update the global registration count stats.
512 $globals->updateNbIns();
513
514 //
515 // Update collateral data sources, and inform watchers by email.
516 //
517
518 // Email the referrer(s) of this new user.
519 $res = XDB::iterRow("SELECT sender, GROUP_CONCAT(email SEPARATOR ', ') AS mails, MAX(last) AS lastDate
520 FROM register_marketing
521 WHERE uid = {?}
522 GROUP BY sender
523 ORDER BY lastDate DESC", $uid);
524 XDB::execute("UPDATE register_mstats
525 SET success = NOW()
526 WHERE uid = {?}", $uid);
527
528 $market = array();
529 while (list($senderid, $maketingEmails, $lastDate) = $res->next()) {
530 $sender = User::getWithUID($senderid);
531 $market[] = " - par {$sender->fullName()} sur $maketingEmails (le plus récemment le $lastDate)";
532 $mymail = new PlMailer('register/marketer.mail.tpl');
533 $mymail->setSubject("$firstname $lastname s'est inscrit à Polytechnique.org !");
534 $mymail->setTo($sender);
535 $mymail->assign('sender', $sender);
536 $mymail->assign('firstname', $firstname);
537 $mymail->assign('lastname', $lastname);
538 $mymail->assign('promo', $promo);
539 $mymail->assign('sex', $sex);
540 $mymail->setTxtBody(wordwrap($msg, 72));
541 $mymail->send();
542 }
543
544 // Email the plat/al administrators about the registration.
545 if ($globals->register->notif) {
546 $mymail = new PlMailer('register/registration.mail.tpl');
547 $mymail->setSubject("Inscription de $firstname $lastname ($promo)");
548 $mymail->assign('firstname', $firstname);
549 $mymail->assign('lastname', $lastname);
550 $mymail->assign('promo', $promo);
551 $mymail->assign('sex', $sex);
552 $mymail->assign('birthdate', $birthdate);
553 $mymail->assign('birthdate_ref', $birthdate_ref);
554 $mymail->assign('forlife', $forlife);
555 $mymail->assign('email', $email);
556 $mymail->assign('logger', S::logger());
557 if (count($market) > 0) {
558 $mymail->assign('market', implode("\n", $market));
559 }
560 $mymail->setTxtBody($msg);
561 $mymail->send();
562 }
563
564 // Remove old pending marketing requests for the new user.
565 Marketing::clear($uid);
566
567 pl_redirect('profile/edit');
568 }
569 }
570
571 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker fenc=utf-8:
572 ?>