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