2 /***************************************************************************
3 * Copyright (C) 2003-2011 Polytechnique.org *
4 * http://opensource.polytechnique.org/ *
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. *
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. *
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 *
19 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
20 ***************************************************************************/
22 class RegisterModule
extends PLModule
27 'register' => $this->make_hook('register', AUTH_PUBLIC
),
28 'register/end' => $this->make_hook('end', AUTH_PUBLIC
),
32 function handler_register($page, $hash = null
)
35 $subState = new PlDict(S
::v('subState', array()));
36 if (!$subState->has('step')) {
37 $subState->set('step', 0);
39 if (!$subState->has('backs')) {
40 $subState->set('backs', new PlDict());
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 - ";
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);
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));
71 XDB
::execute('INSERT INTO register_mstats (uid, sender, success)
72 SELECT m.uid, m.sender, 0
73 FROM register_marketing AS m
75 ON DUPLICATE KEY UPDATE sender = VALUES(sender), success = VALUES(success)',
76 $subState->s('hash'));
80 switch ($subState->i('step')) {
82 $wp = new PlWikiPage('Reference.Charte');
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);
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(*)
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 = {?}",
107 if (!$res->fetchOneCell()) {
108 $error = 'La promotion saisie est incorrecte ou tous les camarades de cette promotion sont inscrits !';
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) . '???');
121 $subState->set('schoolid', '');
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);
135 if ($error !== true
) {
138 $error = createAliases($subState);
139 if ($error === true
) {
141 $subState->set('step', 3);
148 $this->load('register.inc.php');
150 // Validate the email address format and domain.
151 require_once 'emails.inc.php';
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.';
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.";
165 $birth = explode('/', $birth, 3);
166 for ($i = 0; $i < 3; ++
$i)
167 $birth[$i] = intval($birth[$i]);
168 if ($birth[2] < 100) {
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);
180 // Register the optional services requested by the user.
182 foreach (array('ax_letter', 'imap', 'ml_promo', 'nl') as $service) {
183 if (Post
::b($service)) {
184 $services[] = $service;
187 $subState->set('services', $services);
189 // Validate the password.
190 if (!Post
::v('pwhash', false
)) {
191 $error[] = "Le mot de passe n'est pas valide.";
194 // Check if the given email is known as dangerous.
195 $res = XDB
::query("SELECT state, description
197 WHERE email = {?} AND state != 'safe'",
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') {
208 if ($subState->i('watch') != 0) {
209 $alert .= "Inscription d'un utilisateur surveillé - ";
212 if (($bannedIp = check_ip('unsafe'))) {
217 $error = join('<br />', $error);
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'));
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 - ";
231 $alert .= "Tentative d'inscription depuis une IP surveillée";
234 // Prevent banned user from actually registering; save the current state for others.
235 if ($bannedEmail ||
$bannedIp) {
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.";
242 $subState->set('step', 4);
243 if ($subState->v('backs')->count() >= 3) {
244 $alert .= "Fin d'une inscription hésitante.";
246 finishRegistration($subState);
253 $_SESSION['subState'] = $subState->dict();
254 if (!empty($alert)) {
255 send_warning_mail($alert);
258 $page->changeTpl('register/step' . $subState->i('step') . '.tpl');
260 $page->trigError($error);
264 function handler_end($page, $hash = null
)
267 $_SESSION['subState'] = array('step' => 5);
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);
278 $nameTypes = DirEnum
::getOptions(DirEnum
::NAMETYPES
);
279 $nameTypes = array_flip($nameTypes);
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 :</p>
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>
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
;
317 // Prepare the template for display.
318 $page->changeTpl('register/end.tpl');
319 $page->assign('forlife', $forlife);
320 $page->assign('firstname', $firstname);
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)');
336 // Create the user account.
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
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
355 $bestalias, $uid, $mail_domain);
357 XDB
::execute('INSERT INTO email_source_account (email, uid, type, flags, domain)
358 SELECT {?}, {?}, \'alias\', \'\', id
359 FROM email_virtual_domains
361 $emailXorg2, $uid, $mail_domain);
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);
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
);
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';
380 NewsLetter
::forGroup(NewsLetter
::GROUP_AX
)->subscribe($user);
383 NewsLetter
::forGroup(NewsLetter
::GROUP_XORG
)->subscribe($user);
386 Email
::activate_storage($user, 'imap');
389 $r = XDB
::query('SELECT id FROM groups WHERE diminutif = {?}', $yearpromo);
391 $asso_id = $r->fetchOneCell();
392 XDB
::execute('INSERT IGNORE INTO group_members (uid, asso_id)
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.");
407 // Log the registration in the user session.
408 S
::logger($uid)->log('inscription', $email);
409 XDB
::execute("UPDATE register_pending
411 WHERE uid = {?}", $uid);
413 // Congratulate our newly registered user by email.
414 $mymail = new PlMailer('register/success.mail.tpl');
415 $mymail->addTo("\"{$user->fullName()}\" <{$user->forlifeEmail()}>");
417 $mymail->setSubject('Bienvenue parmi les X sur le web !');
419 $mymail->setSubject('Bienvenue sur Polytechnique.org !');
421 $mymail->assign('forlife', $forlife);
422 $mymail->assign('firstname', $firstname);
425 // Index the user, to allow her to appear in searches.
426 Profile
::rebuildSearchTokens($pid);
428 // Notify other users which were watching for her arrival.
429 XDB
::execute('INSERT INTO contacts (uid, contact)
432 WHERE ni_id = {?}', $uid);
433 XDB
::execute('DELETE FROM watch_nonins
434 WHERE ni_id = {?}', $uid);
435 Platal
::session()->updateNbNotifs();
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)
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())
455 if ($promoRegistered->getTotalCount() > 0.2 * $promoFull->getTotalCount()) {
456 $mymail = new PlMailer('admin/forums-promo.mail.tpl');
457 $mymail->assign('promo', $promo);
463 // Update the global registration count stats.
464 $globals->updateNbIns();
467 // Update collateral data sources, and inform watchers by email.
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
475 ORDER BY lastDate DESC", $uid);
476 XDB
::execute("UPDATE register_mstats
478 WHERE uid = {?}", $uid);
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));
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));
512 $mymail->setTxtBody($msg);
516 // Remove old pending marketing requests for the new user.
517 Marketing
::clear($uid);
519 pl_redirect('profile/edit');
523 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: