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