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