Merge branch 'xorg/master' into xorg/f/geocoding
[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,
292 pd.promo, p.sex, p.birthdate_ref, a.type
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, $yearpromo, $sex, $birthdate_ref, $type) = $res->fetchOneRow();
320 $isX = ($type == 'x');
321 $mail_domain = User::$sub_mail_domains[$type] . $globals->mail->domain;
322
323 // Prepare the template for display.
324 $page->changeTpl('register/end.tpl');
325 $page->assign('forlife', $forlife);
326 $page->assign('firstname', $firstname);
327
328 // Check if the user did enter a valid password; if not (or if none is found),
329 // get her an information page.
330 if (Post::has('response')) {
331 $expected_response = sha1("$forlife:$password:" . S::v('challenge'));
332 if (Post::v('response') != $expected_response) {
333 $page->trigError("Mot de passe invalide.");
334 S::logger($uid)->log('auth_fail', 'bad password (register/end)');
335 return;
336 }
337 } else {
338 return;
339 }
340
341 //
342 // Create the user account.
343 //
344 XDB::startTransaction();
345 XDB::execute("UPDATE accounts
346 SET password = {?}, state = 'active',
347 registration_date = NOW(), email = NULL
348 WHERE uid = {?}", $password, $uid);
349 XDB::execute("UPDATE profiles
350 SET birthdate = {?}, last_change = NOW()
351 WHERE pid = {?}", $birthdate, $pid);
352 XDB::execute('INSERT INTO email_source_account (email, uid, type, flags, domain)
353 SELECT {?}, {?}, \'forlife\', \'\', id
354 FROM email_virtual_domains
355 WHERE name = {?}',
356 $forlife, $uid, $mail_domain);
357 XDB::execute('INSERT INTO email_source_account (email, uid, type, flags, domain)
358 SELECT {?}, {?}, \'alias\', \'bestalias\', id
359 FROM email_virtual_domains
360 WHERE name = {?}',
361 $bestalias, $uid, $mail_domain);
362 if ($emailXorg2) {
363 XDB::execute('INSERT INTO email_source_account (email, uid, type, flags, domain)
364 SELECT {?}, {?}, \'alias\', \'\', id
365 FROM email_virtual_domains
366 WHERE name = {?}',
367 $emailXorg2, $uid, $mail_domain);
368 }
369 XDB::commit();
370
371 // Add the registration email address as first and only redirection.
372 require_once 'emails.inc.php';
373 $user = User::getSilentWithUID($uid);
374 $redirect = new Redirect($user);
375 $redirect->add_email($email);
376 fix_bestalias($user);
377
378 // Try to start a session (so the user don't have to log in); we will use
379 // the password available in Post:: to authenticate the user.
380 Platal::session()->start(AUTH_MDP);
381
382 // Subscribe the user to the services she did request at registration time.
383 require_once 'newsletter.inc.php';
384 foreach (explode(',', $services) as $service) {
385 switch ($service) {
386 case 'ax_letter':
387 NewsLetter::forGroup(NewsLetter::GROUP_AX)->subscribe($user);
388 break;
389 case 'nl':
390 NewsLetter::forGroup(NewsLetter::GROUP_XORG)->subscribe($user);
391 break;
392 case 'imap':
393 Email::activate_storage($user, 'imap', Bogo::IMAP_DEFAULT);
394 break;
395 case 'ml_promo':
396 if ($isX) {
397 $r = XDB::query('SELECT id FROM groups WHERE diminutif = {?}', $yearpromo);
398 if ($r->numRows()) {
399 $asso_id = $r->fetchOneCell();
400 XDB::execute('INSERT IGNORE INTO group_members (uid, asso_id)
401 VALUES ({?}, {?})',
402 $uid, $asso_id);
403 try {
404 $mmlist = new MMList($user);
405 $mmlist->subscribe("promo" . $yearpromo);
406 } catch (Exception $e) {
407 PlErrorReport::report($e);
408 $page->trigError("L'inscription à la liste promo" . $yearpromo . " a échouée.");
409 }
410 }
411 }
412 break;
413 }
414 }
415
416 // Log the registration in the user session.
417 S::logger($uid)->log('inscription', $email);
418 XDB::execute("UPDATE register_pending
419 SET hash = 'INSCRIT'
420 WHERE uid = {?}", $uid);
421
422 // Congratulate our newly registered user by email.
423 $mymail = new PlMailer('register/success.mail.tpl');
424 $mymail->addTo("\"{$user->fullName()}\" <{$user->forlifeEmail()}>");
425 if ($isX) {
426 $mymail->setSubject('Bienvenue parmi les X sur le web !');
427 } else {
428 $mymail->setSubject('Bienvenue sur Polytechnique.org !');
429 }
430 $mymail->assign('forlife', $forlife);
431 $mymail->assign('firstname', $firstname);
432 $mymail->send();
433
434 // Index the user, to allow her to appear in searches.
435 Profile::rebuildSearchTokens($pid);
436
437 // Notify other users which were watching for her arrival.
438 XDB::execute('INSERT INTO contacts (uid, contact)
439 SELECT uid, ni_id
440 FROM watch_nonins
441 WHERE ni_id = {?}', $uid);
442 XDB::execute('DELETE FROM watch_nonins
443 WHERE ni_id = {?}', $uid);
444 Platal::session()->updateNbNotifs();
445
446 // Forcibly register the new user on default forums.
447 $registeredForums = array('xorg.general', 'xorg.pa.divers', 'xorg.pa.logements');
448
449 if ($isX) {
450 $promoForum = 'xorg.promo.' . strtolower($promo);
451 $exists = XDB::fetchOneCell('SELECT COUNT(*)
452 FROM forums
453 WHERE name = {?}',
454 $promoForum);
455
456 if ($exists == 0) {
457 // Notify the newsgroup admin of the promotion forum needs be created.
458 $promoFull = new UserFilter(new UFC_Promo('=', UserFilter::DISPLAY, $promo));
459 $promoRegistered = new UserFilter(new PFC_And(
460 new UFC_Promo('=', UserFilter::DISPLAY, $promo),
461 new UFC_Registered(true),
462 new PFC_Not(new UFC_Dead())
463 ));
464 if ($promoRegistered->getTotalCount() > 0.2 * $promoFull->getTotalCount()) {
465 $mymail = new PlMailer('admin/forums-promo.mail.tpl');
466 $mymail->assign('promo', $promo);
467 $mymail->send();
468 }
469 } else {
470 $registeredForums[] = $promoForum;
471 }
472 }
473
474 foreach ($registeredForums as $forum) {
475 XDB::execute("INSERT INTO forum_subs (fid, uid)
476 SELECT fid, {?}
477 FROM forums
478 WHERE name = {?}",
479 $uid, $val);
480 }
481
482 // Update the global registration count stats.
483 $globals->updateNbIns();
484
485 //
486 // Update collateral data sources, and inform watchers by email.
487 //
488
489 // Email the referrer(s) of this new user.
490 $res = XDB::iterRow("SELECT sender, GROUP_CONCAT(email SEPARATOR ', ') AS mails, MAX(last) AS lastDate
491 FROM register_marketing
492 WHERE uid = {?}
493 GROUP BY sender
494 ORDER BY lastDate DESC", $uid);
495 XDB::execute("UPDATE register_mstats
496 SET success = NOW()
497 WHERE uid = {?}", $uid);
498
499 $market = array();
500 while (list($senderid, $maketingEmails, $lastDate) = $res->next()) {
501 $sender = User::getWithUID($senderid);
502 $market[] = " - par {$sender->fullName()} sur $maketingEmails (le plus récemment le $lastDate)";
503 $mymail = new PlMailer('register/marketer.mail.tpl');
504 $mymail->setSubject("$firstname $lastname s'est inscrit à Polytechnique.org !");
505 $mymail->addTo($sender);
506 $mymail->assign('sender', $sender);
507 $mymail->assign('firstname', $firstname);
508 $mymail->assign('lastname', $lastname);
509 $mymail->assign('promo', $promo);
510 $mymail->assign('sex', $sex);
511 $mymail->setTxtBody(wordwrap($msg, 72));
512 $mymail->send();
513 }
514
515 // Email the plat/al administrators about the registration.
516 if ($globals->register->notif) {
517 $mymail = new PlMailer('register/registration.mail.tpl');
518 $mymail->setSubject("Inscription de $firstname $lastname ($promo)");
519 $mymail->assign('firstname', $firstname);
520 $mymail->assign('lastname', $lastname);
521 $mymail->assign('promo', $promo);
522 $mymail->assign('sex', $sex);
523 $mymail->assign('birthdate', $birthdate);
524 $mymail->assign('birthdate_ref', $birthdate_ref);
525 $mymail->assign('forlife', $forlife);
526 $mymail->assign('email', $email);
527 $mymail->assign('logger', S::logger());
528 if (count($market) > 0) {
529 $mymail->assign('market', implode("\n", $market));
530 }
531 $mymail->setTxtBody($msg);
532 $mymail->send();
533 }
534
535 // Remove old pending marketing requests for the new user.
536 Marketing::clear($uid);
537
538 pl_redirect('profile/edit');
539 }
540 }
541
542 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
543 ?>