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