1a88393c34728dcb33eeaa12f68a1d75f9f81832
[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 = null;
35 $subState = new PlDict(S::v('subState', array()));
36 if (!$subState->has('step')) {
37 $subState->set('step', 0);
38 }
39 if (!$subState->has('backs')) {
40 $subState->set('backs', new PlDict());
41 }
42 if (Get::has('back') && Get::i('back') < $subState->i('step')) {
43 $subState->set('step', max(0, Get::i('back')));
44 $subState->v('backs')->set($subState->v('backs')->count() + 1, $subState->dict());
45 $subState->v('backs')->kill('backs');
46 if ($subState->v('backs')->count() == 3) {
47 $alert .= "Tentative d'inscription très hésitante - ";
48 }
49 }
50
51 if ($hash) {
52 $nameTypes = DirEnum::getOptions(DirEnum::NAMETYPES);
53 $nameTypes = array_flip($nameTypes);
54 $res = XDB::query("SELECT a.uid, a.hruid, pnl.name AS lastname, pnf.name 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
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_name AS pnl ON (p.pid = pnl.pid AND pnl.typeid = {?})
65 INNER JOIN profile_name AS pnf ON (p.pid = pnf.pid AND pnf.typeid = {?})
66 WHERE m.hash = {?} AND a.state = 'pending'",
67 $nameTypes['name_ini'], $nameTypes['firstname_ini'], $hash);
68
69 if ($res->numRows() == 1) {
70 $subState->merge($res->fetchOneRow());
71 $subState->set('main_mail_domain', User::$sub_mail_domains[$subState->v('type')]);
72
73 XDB::execute('INSERT INTO register_mstats (uid, sender, success)
74 SELECT m.uid, m.sender, 0
75 FROM register_marketing AS m
76 WHERE m.hash
77 ON DUPLICATE KEY UPDATE sender = VALUES(sender), success = VALUES(success)',
78 $subState->s('hash'));
79 }
80 }
81
82 switch ($subState->i('step')) {
83 case 0:
84 $wp = new PlWikiPage('Reference.Charte');
85 $wp->buildCache();
86 if (Post::has('step1')) {
87 $subState->set('step', 1);
88 if ($subState->has('hash')) {
89 $subState->set('step', 3);
90 $this->load('register.inc.php');
91 createAliases($subState);
92 }
93 }
94 break;
95
96 case 1:
97 if (Post::has('yearpromo')) {
98 $edu_type = Post::t('edu_type');
99 $yearpromo = Post::i('yearpromo');
100 $promo = Profile::$cycle_prefixes[$edu_type] . $yearpromo;
101 $res = XDB::query("SELECT COUNT(*)
102 FROM accounts AS a
103 INNER JOIN account_profiles AS ap ON (a.uid = ap.uid AND FIND_IN_SET('owner', ap.perms))
104 INNER JOIN profiles AS p ON (p.pid = ap.pid)
105 INNER JOIN profile_education AS pe ON (pe.pid = p.pid AND FIND_IN_SET('primary', pe.flags))
106 WHERE a.state = 'pending' AND p.deathdate IS NULL AND pe.promo_year = {?}",
107 $yearpromo);
108
109 if (!$res->fetchOneCell()) {
110 $error = 'La promotion saisie est incorrecte ou tous les camarades de cette promotion sont inscrits !';
111 } else {
112 $subState->set('step', 2);
113 $subState->set('promo', $promo);
114 $subState->set('yearpromo', $yearpromo);
115 $subState->set('edu_type', $edu_type);
116 if ($edu_type == Profile::DEGREE_X) {
117 if ($yearpromo >= 1996 && $yearpromo < 2000) {
118 $subState->set('schoolid', ($yearpromo % 100) * 10 . '???');
119 $subState->set('schoolid_exemple', ($yearpromo % 100) * 10000 + 532);
120 $subState->set('schoolid_exemple_ev2', (($yearpromo + 1) % 100) * 10000 + 532);
121 } elseif($yearpromo >= 2000) {
122 $subState->set('schoolid', 100 + ($yearpromo % 100) . '???');
123 $subState->set('schoolid_exemple', (100 + ($yearpromo % 100)) * 1000 + 532);
124 $subState->set('schoolid_exemple_ev2', (100 + (($yearpromo + 1) % 100)) * 1000 + 532);
125 }
126 }
127 }
128 }
129 break;
130
131 case 2:
132 if (count($_POST)) {
133 $this->load('register.inc.php');
134 $subState->set('firstname', Post::t('firstname'));
135 $subState->set('lastname', Post::t('lastname'));
136 if (Post::has('schoolid')) {
137 $subState->set('schoolid', Post::i('schoolid'));
138 }
139 $error = checkNewUser($subState);
140
141 if ($error !== true) {
142 break;
143 }
144 $error = createAliases($subState);
145 if ($error === true) {
146 unset($error);
147 $subState->set('step', 3);
148 }
149 }
150 break;
151
152 case 3:
153 if (count($_POST)) {
154 $this->load('register.inc.php');
155
156 // Validate the email address format and domain.
157 require_once 'emails.inc.php';
158
159 if (!isvalid_email(Post::v('email'))) {
160 $error[] = "Le champ 'Email' n'est pas valide.";
161 } elseif (!isvalid_email_redirection(Post::v('email'))) {
162 $error[] = $subState->s('forlife') . ' doit renvoyer vers un email existant '
163 . 'valide, en particulier, il ne peut pas être renvoyé vers lui-même.';
164 }
165
166 // Validate the birthday format and range.
167 $birth = Post::t('birthdate');
168 if (!preg_match('@^[0-3]?\d/[01]?\d/(19|20)?\d{2}$@', $birth)) {
169 $error[] = "La 'Date de naissance' n'est pas correcte.";
170 } else {
171 $birth = explode('/', $birth, 3);
172 for ($i = 0; $i < 3; ++$i)
173 $birth[$i] = intval($birth[$i]);
174 if ($birth[2] < 100) {
175 $birth[2] += 1900;
176 }
177 $year = $birth[2];
178 $ref_year = substr($subState->v('birthdateRef'), 0, 4);
179 if (abs($ref_year - $year) > 2) {
180 $error[] = "La 'Date de naissance' n'est pas correcte.";
181 $alert = "Date de naissance incorrecte à l'inscription - ";
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 $subState->set('email_desc', $description);
210 if ($state == 'dangerous') {
211 $bannedEmail = true;
212 }
213 }
214 if ($subState->i('watch') != 0) {
215 $alert .= "Inscription d'un utilisateur surveillé - ";
216 }
217
218 if (($bannedIp = check_ip('unsafe'))) {
219 unset($error);
220 }
221
222 if (isset($error)) {
223 $error = join('<br />', $error);
224 } else {
225 $subState->set('birthdate', sprintf("%04d-%02d-%02d",
226 intval($birth[2]), intval($birth[1]), intval($birth[0])));
227 $subState->set('email', Post::t('email'));
228 $subState->set('password', Post::t('pwhash'));
229
230 // Update the current alert if the birthdate is incorrect,
231 // or if the IP address of the user has been banned.
232 if ($subState->s('birthdateRef') != '0000-00-00'
233 && $subState->s('birthdateRef') != $subState->s('birthdate')) {
234 $alert .= "Date de naissance incorrecte à l'inscription - ";
235 }
236 if ($bannedIp) {
237 $alert .= "Tentative d'inscription depuis une IP surveillée";
238 }
239
240 // Prevent banned user from actually registering; save the current state for others.
241 if ($bannedEmail || $bannedIp) {
242 global $globals;
243 $error = "Une erreur s'est produite lors de l'inscription."
244 . " Merci de contacter <a href='mailto:register@{$globals->mail->domain}>"
245 . " register@{$globals->mail->domain}</a>"
246 . " pour nous faire part de cette erreur.";
247 } else {
248 $subState->set('step', 4);
249 if ($subState->v('backs')->count() >= 3) {
250 $alert .= "Fin d'une inscription hésitante.";
251 }
252 finishRegistration($subState);
253 }
254 }
255 }
256 break;
257 }
258
259 $_SESSION['subState'] = $subState->dict();
260 if (!empty($alert)) {
261 send_warning_mail($alert);
262 }
263
264 $page->changeTpl('register/step' . $subState->i('step') . '.tpl');
265 if (isset($error)) {
266 $page->trigError($error);
267 }
268 }
269
270 function handler_end($page, $hash = null)
271 {
272 global $globals;
273 $_SESSION['subState'] = array('step' => 5);
274
275 // Reject registration requests from unsafe IP addresses (and remove the
276 // registration information from the database, to prevent IP changes).
277 if (check_ip('unsafe')) {
278 send_warning_mail('Une IP surveillée a tenté de finaliser son inscription.');
279 XDB::execute("DELETE FROM register_pending
280 WHERE hash = {?} AND hash != 'INSCRIT'", $hash);
281 return PL_FORBIDDEN;
282 }
283
284 $nameTypes = DirEnum::getOptions(DirEnum::NAMETYPES);
285 $nameTypes = array_flip($nameTypes);
286
287 // Retrieve the pre-registration information using the url-provided
288 // authentication token.
289 $res = XDB::query("SELECT r.uid, p.pid, r.forlife, r.bestalias, r.mailorg2,
290 r.password, r.email, r.services, r.naissance,
291 pnl.name AS lastname, pnf.name AS firstname, pe.promo_year AS yearpromo,
292 pd.promo, p.sex, p.birthdate_ref, a.type AS eduType
293 FROM register_pending AS r
294 INNER JOIN accounts AS a ON (r.uid = a.uid)
295 INNER JOIN account_profiles AS ap ON (a.uid = ap.uid AND FIND_IN_SET('owner', ap.perms))
296 INNER JOIN profiles AS p ON (p.pid = ap.pid)
297 INNER JOIN profile_name AS pnl ON (p.pid = pnl.pid AND pnl.typeid = {?})
298 INNER JOIN profile_name AS pnf ON (p.pid = pnf.pid AND pnf.typeid = {?})
299 INNER JOIN profile_display AS pd ON (p.pid = pd.pid)
300 INNER JOIN profile_education AS pe ON (pe.pid = p.pid AND FIND_IN_SET('primary', pe.flags))
301 WHERE hash = {?} AND hash != 'INSCRIT' AND a.state = 'pending'",
302 $nameTypes['name_ini'], $nameTypes['firstname_ini'], $hash);
303 if (!$hash || $res->numRows() == 0) {
304 $page->kill("<p>Cette adresse n'existe pas, ou plus, sur le serveur.</p>
305 <p>Causes probables&nbsp;:</p>
306 <ol>
307 <li>Vérifie que tu visites l'adresse du dernier
308 email reçu s'il y en a eu plusieurs.</li>
309 <li>Tu as peut-être mal copié l'adresse reçue par
310 email, vérifie-la à la main.</li>
311 <li>Tu as peut-être attendu trop longtemps pour
312 confirmer. Les pré-inscriptions sont annulées
313 tous les 30 jours.</li>
314 <li>Tu es en fait déjà inscrit.</li>
315 </ol>");
316 }
317
318 list($uid, $pid, $forlife, $bestalias, $emailXorg2, $password, $email, $services,
319 $birthdate, $lastname, $firstname, $promo, $sex, $birthdate_ref, $eduType) = $res->fetchOneRow();
320 $isX = ($eduType == 'x');
321 // We need the expected promotion here. Thus we remove pending display.
322 $promo = str_replace(' (en cours)', $yearpromo, $promo);
323 $mail_domain = User::$sub_mail_domains[$eduType] . $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
379 // Try to start a session (so the user don't have to log in); we will use
380 // the password available in Post:: to authenticate the user.
381 Platal::session()->start(AUTH_MDP);
382
383 // Subscribe the user to the services she did request at registration time.
384 foreach (explode(',', $services) as $service) {
385 require_once 'newsletter.inc.php';
386 switch ($service) {
387 case 'ax_letter':
388 NewsLetter::forGroup(NewsLetter::GROUP_AX)->subscribe($user);
389 break;
390 case 'nl':
391 NewsLetter::forGroup(NewsLetter::GROUP_XORG)->subscribe($user);
392 break;
393 case 'imap':
394 Email::activate_storage($user, 'imap');
395 break;
396 case 'ml_promo':
397 if ($isX) {
398 $r = XDB::query('SELECT id FROM groups WHERE diminutif = {?}', $yearpromo);
399 if ($r->numRows()) {
400 $asso_id = $r->fetchOneCell();
401 XDB::execute('INSERT IGNORE INTO group_members (uid, asso_id)
402 VALUES ({?}, {?})',
403 $uid, $asso_id);
404 try {
405 $mmlist = new MMList($user);
406 $mmlist->subscribe("promo" . $yearpromo);
407 } catch (Exception $e) {
408 PlErrorReport::report($e);
409 $page->trigError("L'inscription à la liste promo" . $yearpromo . " a échouée.");
410 }
411 }
412 }
413 break;
414 }
415 }
416
417 // Log the registration in the user session.
418 S::logger($uid)->log('inscription', $email);
419 XDB::execute("UPDATE register_pending
420 SET hash = 'INSCRIT'
421 WHERE uid = {?}", $uid);
422
423 // Congratulate our newly registered user by email.
424 $mymail = new PlMailer('register/success.mail.tpl');
425 $mymail->addTo("\"{$user->fullName()}\" <{$user->forlifeEmail()}>");
426 if ($isX) {
427 $mymail->setSubject('Bienvenue parmi les X sur le web !');
428 } else {
429 $mymail->setSubject('Bienvenue sur Polytechnique.org !');
430 }
431 $mymail->assign('forlife', $forlife);
432 $mymail->assign('firstname', $firstname);
433 $mymail->send();
434
435 // Index the user, to allow her to appear in searches.
436 Profile::rebuildSearchTokens($pid);
437
438 // Notify other users which were watching for her arrival.
439 XDB::execute('INSERT INTO contacts (uid, contact)
440 SELECT uid, ni_id
441 FROM watch_nonins
442 WHERE ni_id = {?}', $uid);
443 XDB::execute('DELETE FROM watch_nonins
444 WHERE ni_id = {?}', $uid);
445 Platal::session()->updateNbNotifs();
446
447 // Forcibly register the new user on default forums.
448 $promoForum = 'xorg.promo.' . strtolower($promo);
449 $registeredForums = array('xorg.general', 'xorg.pa.divers', 'xorg.pa.logements', $promoForum);
450 foreach ($registeredForums as $forum) {
451 XDB::execute("INSERT INTO forum_subs (fid, uid)
452 SELECT fid, {?}
453 FROM forums
454 WHERE name = {?}",
455 $uid, $val);
456
457 // Notify the newsgroup admin of the promotion forum needs be created.
458 if (XDB::affectedRows() == 0 && $forum == $promoForum) {
459 $promoFull = new UserFilter(new UFC_Promo('=', UserFilter::DISPLAY, $promo));
460 $promoRegistered = new UserFilter(new PFC_And(
461 new UFC_Promo('=', UserFilter::DISPLAY, $promo),
462 new UFC_Registered(true),
463 new PFC_Not(new UFC_Dead())
464 ));
465 if ($promoRegistered->getTotalCount() > 0.2 * $promoFull->getTotalCount()) {
466 $mymail = new PlMailer('admin/forums-promo.mail.tpl');
467 $mymail->assign('promo', $promo);
468 $mymail->send();
469 }
470 }
471 }
472
473 // Update the global registration count stats.
474 $globals->updateNbIns();
475
476 //
477 // Update collateral data sources, and inform watchers by email.
478 //
479
480 // Email the referrer(s) of this new user.
481 $res = XDB::iterRow("SELECT sender, GROUP_CONCAT(email SEPARATOR ', ') AS mails, MAX(last) AS lastDate
482 FROM register_marketing
483 WHERE uid = {?}
484 GROUP BY sender
485 ORDER BY lastDate DESC", $uid);
486 XDB::execute("UPDATE register_mstats
487 SET success = NOW()
488 WHERE uid = {?}", $uid);
489
490 $market = array();
491 while (list($senderid, $maketingEmails, $lastDate) = $res->next()) {
492 $sender = User::getWithUID($senderid);
493 $market[] = " - par {$sender->fullName()} sur $maketingEmails (le plus récemment le $lastDate)";
494 $mymail = new PlMailer('register/marketer.mail.tpl');
495 $mymail->setSubject("$firstname $lastname s'est inscrit à Polytechnique.org !");
496 $mymail->addTo($sender);
497 $mymail->assign('sender', $sender);
498 $mymail->assign('firstname', $firstname);
499 $mymail->assign('lastname', $lastname);
500 $mymail->assign('promo', $promo);
501 $mymail->assign('sex', $sex);
502 $mymail->setTxtBody(wordwrap($msg, 72));
503 $mymail->send();
504 }
505
506 // Email the plat/al administrators about the registration.
507 if ($globals->register->notif) {
508 $mymail = new PlMailer('register/registration.mail.tpl');
509 $mymail->setSubject("Inscription de $firstname $lastname ($promo)");
510 $mymail->assign('firstname', $firstname);
511 $mymail->assign('lastname', $lastname);
512 $mymail->assign('promo', $promo);
513 $mymail->assign('sex', $sex);
514 $mymail->assign('birthdate', $birthdate);
515 $mymail->assign('birthdate_ref', $birthdate_ref);
516 $mymail->assign('forlife', $forlife);
517 $mymail->assign('email', $email);
518 $mymail->assign('logger', S::logger());
519 if (count($market) > 0) {
520 $mymail->assign('market', implode("\n", $market));
521 }
522 $mymail->setTxtBody($msg);
523 $mymail->send();
524 }
525
526 // Remove old pending marketing requests for the new user.
527 Marketing::clear($uid);
528
529 pl_redirect('profile/edit');
530 }
531 }
532
533 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
534 ?>