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