REPLACE INTO should only be used if the data deletion is wanted.
[platal.git] / modules / register.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2010 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
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 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 $services = array();
175 foreach (array('ax_letter', 'imap', 'ml_promo', 'nl') as $service) {
176 if (Post::b($service)) {
177 $services[] = $service;
178 }
179 }
180 $subState->set('services', $services);
181
182 // Validate the password.
183 if (!Post::v('pwhash', false)) {
184 $error[] = "Le mot de passe n'est pas valide.";
185 }
186
187 // Check if the given email is known as dangerous.
188 $res = XDB::query("SELECT state, description
189 FROM email_watch
190 WHERE email = {?} AND state != 'safe'",
191 Post::v('email'));
192 $bannedEmail = false;
193 if ($res->numRows()) {
194 list($state, $description) = $res->fetchOneRow();
195 $alert .= "Email surveillé proposé à l'inscription - ";
196 $subState->set('email_desc', $description);
197 if ($state == 'dangerous') {
198 $bannedEmail = true;
199 }
200 }
201 if ($subState->i('watch') != 0) {
202 $alert .= "Inscription d'un utilisateur surveillé - ";
203 }
204
205 if (($bannedIp = check_ip('unsafe'))) {
206 unset($error);
207 }
208
209 if (isset($error)) {
210 $error = join('<br />', $error);
211 } else {
212 $subState->set('birthdate', sprintf("%04d-%02d-%02d",
213 intval($birth[2]), intval($birth[1]), intval($birth[0])));
214 $subState->set('email', Post::t('email'));
215 $subState->set('password', Post::t('pwhash'));
216
217 // Update the current alert if the birthdate is incorrect,
218 // or if the IP address of the user has been banned.
219 if ($subState->s('birthdateRef') != '0000-00-00'
220 && $subState->s('birthdateRef') != $subState->s('birthdate')) {
221 $alert .= "Date de naissance incorrecte à l'inscription - ";
222 }
223 if ($bannedIp) {
224 $alert .= "Tentative d'inscription depuis une IP surveillée";
225 }
226
227 // Prevent banned user from actually registering; save the current state for others.
228 if ($bannedEmail || $bannedIp) {
229 global $globals;
230 $error = "Une erreur s'est produite lors de l'inscription."
231 . " Merci de contacter <a href='mailto:register@{$globals->mail->domain}>"
232 . " register@{$globals->mail->domain}</a>"
233 . " pour nous faire part de cette erreur.";
234 } else {
235 $subState->set('step', 4);
236 if ($subState->v('backs')->count() >= 3) {
237 $alert .= "Fin d'une inscription hésitante.";
238 }
239 finishRegistration($subState);
240 }
241 }
242 }
243 break;
244 }
245
246 $_SESSION['subState'] = $subState->dict();
247 if (!empty($alert)) {
248 send_warning_mail($alert);
249 }
250
251 $page->changeTpl('register/step' . $subState->i('step') . '.tpl');
252 $page->addJsLink('password.js');
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
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) = $res->fetchOneRow();
307 $yearpromo = substr($promo, 1, 4);
308
309 // Prepare the template for display.
310 $page->changeTpl('register/end.tpl');
311 $page->addJsLink('do_challenge_response_logged.js');
312 $page->assign('forlife', $forlife);
313 $page->assign('firstname', $firstname);
314
315 // Check if the user did enter a valid password; if not (or if none is found),
316 // get her an information page.
317 if (Post::has('response')) {
318 $expected_response = sha1("$forlife:$password:" . S::v('challenge'));
319 if (Post::v('response') != $expected_response) {
320 $page->trigError("Mot de passe invalide.");
321 S::logger($uid)->log('auth_fail', 'bad password (register/end)');
322 return;
323 }
324 } else {
325 return;
326 }
327
328 //
329 // Create the user account.
330 //
331 XDB::execute("UPDATE accounts
332 SET password = {?}, state = 'active',
333 registration_date = NOW(), email = NULL
334 WHERE uid = {?}", $password, $uid);
335 XDB::execute("UPDATE profiles
336 SET birthdate = {?}, last_change = NOW()
337 WHERE pid = {?}", $birthdate, $pid);
338 XDB::execute("INSERT INTO aliases (uid, alias, type)
339 VALUES ({?}, {?}, 'a_vie')", $uid, $forlife);
340 XDB::execute("INSERT INTO aliases (uid, alias, type, flags)
341 VALUES ({?}, {?}, 'alias', 'bestalias')", $uid, $bestalias);
342 if ($emailXorg2) {
343 XDB::execute("INSERT INTO aliases (uid, alias, type)
344 VALUES ({?}, {?}, 'alias')", $uid, $emailXorg2);
345 }
346
347 // Add the registration email address as first and only redirection.
348 require_once 'emails.inc.php';
349 $user = User::getSilentWithUID($uid);
350 $redirect = new Redirect($user);
351 $redirect->add_email($email);
352
353 // Try to start a session (so the user don't have to log in); we will use
354 // the password available in Post:: to authenticate the user.
355 $success = Platal::session()->start(AUTH_MDP);
356
357 // Subscribe the user to the services she did request at registration time.
358 foreach (explode(',', $services) as $service) {
359 switch ($service) {
360 case 'ax_letter':
361 Platal::load('axletter', 'axletter.inc.php');
362 AXLetter::subscribe($uid);
363 break;
364 case 'imap':
365 $storage = new EmailStorage($user, 'imap');
366 $storage->activate();
367 break;
368 case 'ml_promo':
369 $r = XDB::query('SELECT id FROM groups WHERE diminutif = {?}', $yearpromo);
370 if ($r->numRows()) {
371 $asso_id = $r->fetchOneCell();
372 XDB::execute('INSERT INTO group_members (uid, asso_id)
373 VALUES ({?}, {?})',
374 $uid, $asso_id);
375 $mmlist = new MMList($uid, S::v('password'));
376 $mmlist->subscribe("promo" . S::v('promo'));
377 }
378 break;
379 case 'nl':
380 require_once 'newsletter.inc.php';
381 NewsLetter::subscribe($uid);
382 break;
383 }
384 }
385
386 // Log the registration in the user session.
387 S::logger($uid)->log('inscription', $email);
388 XDB::execute("UPDATE register_pending
389 SET hash = 'INSCRIT'
390 WHERE uid = {?}", $uid);
391
392 // Congratulate our newly registered user by email.
393 $mymail = new PlMailer('register/success.mail.tpl');
394 $mymail->assign('forlife', $forlife);
395 $mymail->assign('firstname', $firstname);
396 $mymail->send();
397
398 // Index the user, to allow her to appear in searches.
399 Profile::rebuildSearchTokens($pid);
400
401 // Notify other users which were watching for her arrival.
402 XDB::execute('INSERT INTO contacts (uid, contact)
403 SELECT uid, ni_id
404 FROM watch_nonins
405 WHERE ni_id = {?}', $uid);
406 XDB::execute('DELETE FROM watch_nonins
407 WHERE ni_id = {?}', $uid);
408 Platal::session()->updateNbNotifs();
409
410 // Forcibly register the new user on default forums.
411 $promoForum = 'xorg.promo.' . strtolower($promo);
412 $registeredForums = array('xorg.general', 'xorg.pa.divers', 'xorg.pa.logements', $promoForum);
413 foreach ($registeredForums as $forum) {
414 XDB::execute("INSERT INTO forum_subs (fid, uid)
415 SELECT fid, {?}
416 FROM forums
417 WHERE name = {?}",
418 $uid, $val);
419
420 // Notify the newsgroup admin of the promotion forum needs be created.
421 if (XDB::affectedRows() == 0 && $forum == $promoForum) {
422 $promoFull = new UserFilter(new UFC_Promo('=', UserFilter::DISPLAY, $promo));
423 $promoRegistered = new UserFilter(new PFC_And(
424 new UFC_Promo('=', UserFilter::DISPLAY, $promo),
425 new UFC_Registered(true),
426 new PFC_Not(new UFC_Dead())
427 ));
428 if ($promoRegistered->getTotalCount() > 0.2 * $promoFull->getTotalCount()) {
429 $mymail = new PlMailer('admin/forums-promo.mail.tpl');
430 $mymail->assign('promo', $promo);
431 $mymail->send();
432 }
433 }
434 }
435
436 // Update the global registration count stats.
437 $globals->updateNbIns();
438
439 //
440 // Update collateral data sources, and inform watchers by email.
441 //
442
443 // Email the referrer(s) of this new user.
444 $res = XDB::iterRow("SELECT sender, GROUP_CONCAT(email SEPARATOR ', ') AS mails, MAX(last) AS lastDate
445 FROM register_marketing
446 WHERE uid = {?}
447 GROUP BY sender
448 ORDER BY lastDate DESC", $uid);
449 XDB::execute("UPDATE register_mstats
450 SET success = NOW()
451 WHERE uid = {?}", $uid);
452
453 $market = array();
454 while (list($senderid, $maketingEmails, $lastDate) = $res->next()) {
455 $sender = User::getWithUID($senderid);
456 $market[] = " - par {$sender->fullName()} sur $maketingEmails (le plus récemment le $lastDate)";
457 $mymail = new PlMailer('register/marketer.mail.tpl');
458 $mymail->setSubject("$firstname $lastname s'est inscrit à Polytechnique.org !");
459 $mymail->addTo($sender);
460 $mymail->assign('sender', $sender);
461 $mymail->assign('firstname', $firstname);
462 $mymail->assign('lastname', $lastname);
463 $mymail->assign('promo', $promo);
464 $mymail->assign('sex', $sex);
465 $mymail->setTxtBody(wordwrap($msg, 72));
466 $mymail->send();
467 }
468
469 // Email the plat/al administrators about the registration.
470 if ($globals->register->notif) {
471 $mymail = new PlMailer('register/registration.mail.tpl');
472 $mymail->setSubject("Inscription de $firstname $lastname ($promo)");
473 $mymail->assign('firstname', $firstname);
474 $mymail->assign('lastname', $lastname);
475 $mymail->assign('promo', $promo);
476 $mymail->assign('sex', $sex);
477 $mymail->assign('birthdate', $birthdate);
478 $mymail->assign('birthdate_ref', $birthdate_ref);
479 $mymail->assign('forlife', $forlife);
480 $mymail->assign('email', $email);
481 $mymail->assign('logger', S::logger());
482 if (count($market) > 0) {
483 $mymail->assign('market', implode("\n", $market));
484 }
485 $mymail->setTxtBody($msg);
486 $mymail->send();
487 }
488
489 // Remove old pending marketing requests for the new user.
490 Marketing::clear($uid);
491
492 pl_redirect('profile/edit');
493 }
494 }
495
496 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
497 ?>