Merge commit 'origin/master' into fusionax
[platal.git] / modules / register.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2009 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 'register/end.php' => $this->make_hook('end_old', AUTH_PUBLIC),
30 'register/success' => $this->make_hook('success', AUTH_MDP),
31 'register/save' => $this->make_hook('save', AUTH_MDP),
32 );
33 }
34
35 function handler_register(&$page, $hash = null)
36 {
37 $alert = null;
38 $sub_state = S::v('sub_state', Array());
39 if (!isset($sub_state['step'])) {
40 $sub_state['step'] = 0;
41 }
42 if (!isset($sub_state['backs'])) {
43 $sub_state['backs'] = array();
44 }
45 if (Get::has('back') && Get::i('back') < $sub_state['step']) {
46 $sub_state['step'] = max(0,Get::i('back'));
47 $state = $sub_state;
48 unset($state['backs']);
49 $sub_state['backs'][] = $state;
50 if (count($sub_state['backs']) == 3) {
51 $alert .= "Tentative d'inscription tres hesitante - ";
52 }
53 }
54
55 // Compatibility with old sources, keep it atm
56 if (!$hash && Env::has('hash')) {
57 $hash = Env::v('hash');
58 }
59
60 if ($hash) {
61 $res = XDB::query(
62 "SELECT m.uid, u.promo, u.nom, u.prenom, u.matricule, u.naissance_ini, FIND_IN_SET('watch', u.flags)
63 FROM register_marketing AS m
64 INNER JOIN auth_user_md5 AS u ON u.user_id = m.uid
65 WHERE m.hash={?}", $hash);
66 if (list($uid, $promo, $nom, $prenom, $ourmat, $naiss, $watch) = $res->fetchOneRow()) {
67 $sub_state['uid'] = $uid;
68 $sub_state['hash'] = $hash;
69 $sub_state['promo'] = $promo;
70 $sub_state['nom'] = $nom;
71 $sub_state['prenom'] = $prenom;
72 $sub_state['ourmat'] = $ourmat;
73 $sub_state['watch'] = $watch;
74 $sub_state['naissance_ini'] = $naiss;
75
76 XDB::execute(
77 "REPLACE INTO register_mstats (uid,sender,success)
78 SELECT m.uid, m.sender, 0
79 FROM register_marketing AS m
80 WHERE m.hash", $sub_state['hash']);
81 }
82 }
83
84 switch ($sub_state['step']) {
85 case 0:
86 $wp = new PlWikiPage('Reference.Charte');
87 $wp->buildCache();
88 if (Post::has('step1')) {
89 $sub_state['step'] = 1;
90 if (isset($sub_state['hash'])) {
91 $sub_state['step'] = 3;
92 $this->load('register.inc.php');
93 create_aliases($sub_state);
94 }
95 }
96 break;
97
98 case 1:
99 if (Post::has('promo')) {
100 $promo = Post::i('promo');
101 $res = XDB::query("SELECT COUNT(*)
102 FROM auth_user_md5
103 WHERE perms='pending' AND deces = '0000-00-00'
104 AND promo = {?}",
105 $promo);
106 if (!$res->fetchOneCell()) {
107 $err = "La promotion saisie est incorrecte ou tous les camardes de cette promo sont inscrits !";
108 } else {
109 $sub_state['step'] = 2;
110 $sub_state['promo'] = $promo;
111 if ($promo >= 1996 && $promo<2000) {
112 $sub_state['mat'] = ($promo % 100)*10 . '???';
113 } elseif($promo >= 2000) {
114 $sub_state['mat'] = 100 + ($promo % 100) . '???';
115 }
116 }
117 }
118 break;
119
120 case 2:
121 if (count($_POST)) {
122 $this->load('register.inc.php');
123 $sub_state['prenom'] = Post::v('prenom');
124 $sub_state['nom'] = Post::v('nom');
125 $sub_state['mat'] = Post::v('mat');
126 $err = check_new_user($sub_state);
127
128 if ($err !== true) { break; }
129 $err = create_aliases($sub_state);
130 if ($err === true) {
131 unset($err);
132 $sub_state['step'] = 3;
133 }
134 }
135 break;
136
137 case 3:
138 if (count($_POST)) {
139 $this->load('register.inc.php');
140 require_once 'emails.inc.php';
141 if (!isvalid_email(Post::v('email'))) {
142 $err[] = "Le champ 'E-mail' n'est pas valide.";
143 } elseif (!isvalid_email_redirection(Post::v('email'))) {
144 $err[] = $sub_state['forlife']." doit renvoyer vers un email existant ".
145 "valide, en particulier, il ne peut pas être renvoyé vers lui-même.";
146 }
147 $birth = trim(Env::v('naissance'));
148 if (!preg_match('@^[0-3]?\d/[01]?\d/(19|20)?\d{2}$@', $birth)) {
149 $err[] = "La 'Date de naissance' n'est pas correcte.";
150 } else {
151 $birth = explode('/', $birth, 3);
152 for ($i = 0; $i < 3; $i++)
153 $birth[$i] = intval($birth[$i]);
154 if ($birth[2] < 100) $birth[2] += 1900;
155 $year = $birth[2];
156 $promo = (int)$sub_state['promo'];
157 if ($year > $promo - 15 || $year < $promo - 30) {
158 $err[] = "La 'Date de naissance' n'est pas correcte.";
159 $alert = "Date de naissance incorrecte a l'inscription - ";
160 $sub_state['wrong_naissance'] = $birth;
161 }
162 }
163
164 // Check if the given email is known as dangerous
165 $res = XDB::query("SELECT w.state, w.description
166 FROM emails_watch AS w
167 WHERE w.email = {?} AND w.state != 'safe'",
168 Post::v('email'));
169 $email_banned = false;
170 if ($res->numRows()) {
171 list($state, $description) = $res->fetchOneRow();
172 $alert .= "Email surveille propose a l'inscription - ";
173 $sub_state['email_desc'] = $description;
174 if ($state == 'dangerous') {
175 $email_banned = true;
176 }
177 }
178 if ($sub_state['watch']) {
179 $alert .= "Inscription d'un utilisateur surveillé - ";
180 }
181
182 if (check_ip('unsafe')) {
183 unset($err);
184 }
185
186 if (isset($err)) {
187 $err = join('<br />', $err);
188 } else {
189 $sub_state['naissance'] = sprintf("%04d-%02d-%02d",
190 intval($birth[2]), intval($birth[1]), intval($birth[0]));
191 if ($sub_state['naissance_ini'] != '0000-00-00' && $sub_state['naissance'] != $sub_state['naissance_ini']) {
192 $alert .= "Date de naissance incorrecte à l'inscription - ";
193 }
194 $sub_state['email'] = Post::v('email');
195 $ip_banned = check_ip('unsafe');
196 if ($ip_banned) {
197 $alert .= "Tentative d'inscription depuis une IP surveillee";
198 }
199 if ($email_banned || $ip_banned) {
200 global $globals;
201 $err = "Une erreur s'est produite lors de l'inscription."
202 . " Merci de contacter <a href='mailto:register@{$globals->mail->domain}>"
203 . " register@{$globals->mail->domain}</a>"
204 . " pour nous faire part de cette erreur";
205 } else {
206 $sub_state['step'] = 4;
207 if (count($sub_state['backs']) >= 3) {
208 $alert .= "Fin d'une inscription hésitante";
209 }
210 finish_ins($sub_state);
211 }
212 }
213 }
214 break;
215 }
216
217 $_SESSION['sub_state'] = $sub_state;
218 if (!empty($alert)) {
219 send_warning_mail($alert);
220 }
221 $page->changeTpl('register/step'.intval($sub_state['step']).'.tpl');
222 if (isset($err)) {
223 $page->trigError($err);
224 }
225 }
226
227 function handler_end_old(&$page)
228 {
229 return $this->handler_end($page, Env::v('hash'));
230 }
231
232 function handler_end(&$page, $hash = null)
233 {
234 global $globals;
235
236
237 $page->changeTpl('register/end.tpl');
238 $_SESSION['sub_state'] = array('step' => 5);
239
240 if (check_ip('unsafe')) {
241 send_warning_mail('Une IP surveillée a tenté de finaliser son inscription');
242 XDB::execute('DELETE FROM register_pending
243 WHERE hash = {?} AND hash != \'INSCRIT\'', $hash);
244 return PL_FORBIDDEN;
245 }
246
247 require_once('user.func.inc.php');
248
249 if ($hash) {
250 $res = XDB::query(
251 "SELECT r.uid, r.forlife, r.bestalias, r.mailorg2,
252 r.password, r.email, r.naissance, u.nom, u.prenom,
253 u.promo, FIND_IN_SET('femme', u.flags), u.naissance_ini
254 FROM register_pending AS r
255 INNER JOIN auth_user_md5 AS u ON r.uid = u.user_id
256 WHERE hash={?} AND hash!='INSCRIT'", $hash);
257 }
258
259 if (!$hash || !list($uid, $forlife, $bestalias, $mailorg2, $password, $email,
260 $naissance, $nom, $prenom, $promo, $femme, $naiss_ini) = $res->fetchOneRow())
261 {
262 $page->kill("<p>Cette adresse n'existe pas, ou plus, sur le serveur.</p>
263 <p>Causes probables :</p>
264 <ol>
265 <li>Vérifie que tu visites l'adresse du dernier
266 e-mail reçu s'il y en a eu plusieurs.</li>
267 <li>Tu as peut-être mal copié l'adresse reçue par
268 mail, vérifie-la à la main.</li>
269 <li>Tu as peut-être attendu trop longtemps pour
270 confirmer. Les pré-inscriptions sont annulées
271 tous les 30 jours.</li>
272 <li>Tu es en fait déjà inscrit.</li>
273 </ol>");
274 }
275
276
277
278 /***********************************************************/
279 /****************** REALLY CREATE ACCOUNT ******************/
280 /***********************************************************/
281
282 XDB::execute('UPDATE auth_user_md5
283 SET password={?}, perms="user",
284 date=NOW(), naissance={?}, date_ins = NOW()
285 WHERE user_id={?}', $password, $naissance, $uid);
286 XDB::execute('REPLACE INTO auth_user_quick (user_id) VALUES ({?})', $uid);
287 XDB::execute('INSERT INTO aliases (id,alias,type)
288 VALUES ({?}, {?}, "a_vie")', $uid,
289 $forlife);
290 XDB::execute('INSERT INTO aliases (id,alias,type,flags)
291 VALUES ({?}, {?}, "alias", "bestalias")',
292 $uid, $bestalias);
293 if ($mailorg2) {
294 XDB::execute('INSERT INTO aliases (id,alias,type)
295 VALUES ({?}, {?}, "alias")', $uid,
296 $mailorg2);
297 }
298
299 require_once('emails.inc.php');
300 $user = User::getSilent($uid);
301 $redirect = new Redirect($user);
302 $redirect->add_email($email);
303
304 // on cree un objet logger et on log l'inscription
305 S::logger($uid)->log('inscription', $email);
306 XDB::execute('UPDATE register_pending SET hash="INSCRIT" WHERE uid={?}', $uid);
307
308
309 $mymail = new PlMailer('register/inscription.reussie.tpl');
310 $mymail->assign('forlife', $forlife);
311 $mymail->assign('prenom', $prenom);
312 $mymail->send();
313
314 // Enable search on the user
315 require_once('user.func.inc.php');
316 user_reindex($uid);
317
318 // Add notification for people looking for this registration
319 require_once 'notifs.inc.php';
320 register_watch_op($uid, WATCH_INSCR);
321 inscription_notifs_base($uid);
322
323 // Default registration on forums
324 $p_for = 'xorg.promo.x' . $promo;
325 $cible = array('xorg.general', 'xorg.pa.divers', 'xorg.pa.logements', $p_for);
326 foreach ($cible as $val) {
327 XDB::execute("INSERT INTO forums.abos (fid,uid)
328 SELECT fid, {?} FROM forums.list WHERE nom={?}", $uid, $val);
329 if (XDB::affectedRows() == 0 && $val == $p_for) {
330 $res = XDB::query("SELECT SUM(perms IN ('admin','user') AND deces = 0), COUNT(*)
331 FROM auth_user_md5
332 WHERE promo = {?}", $promo);
333 list($effau, $effid) = $res->fetchOneRow();
334 if (5 * $effau > $effid) { // +
335 $mymail = new PlMailer('admin/forums-promo.mail.tpl');
336 $mymail->assign('promo', $promo);
337 $mymail->send();
338 }
339 }
340 }
341
342 // update number of subscribers (perms has changed)
343 $globals->updateNbIns();
344
345 if (!Platal::session()->startWeakSession($uid)) {
346 return PL_FORBIDDEN;
347 }
348
349 /***********************************************************/
350 /************* envoi d'un mail au démarcheur ***************/
351 /***********************************************************/
352 $res = XDB::iterRow(
353 "SELECT sa.alias, IF(s.nom_usage,s.nom_usage,s.nom) AS nom,
354 s.prenom, FIND_IN_SET('femme', s.flags) AS femme,
355 GROUP_CONCAT(m.email SEPARATOR ', ') AS mails, MAX(m.last) AS dateDernier
356 FROM register_marketing AS m
357 INNER JOIN auth_user_md5 AS s ON ( m.sender = s.user_id )
358 INNER JOIN aliases AS sa ON ( sa.id = m.sender
359 AND FIND_IN_SET('bestalias', sa.flags) )
360 WHERE m.uid = {?}
361 GROUP BY m.sender
362 ORDER BY dateDernier DESC", $uid);
363 XDB::execute("UPDATE register_mstats SET success=NOW() WHERE uid={?}", $uid);
364
365 $market = array();
366 while (list($salias, $snom, $sprenom, $sfemme, $mails, $dateDernier) = $res->next()) {
367 $market[] = " - par $snom $sprenom sur $mails (le plus récemment le $dateDernier)";
368 $mymail = new PlMailer();
369 $mymail->setSubject("$prenom $nom s'est inscrit à Polytechnique.org !");
370 $mymail->setFrom('"Marketing Polytechnique.org" <register@' . $globals->mail->domain . '>');
371 $mymail->addTo("\"$sprenom $snom\" <$salias@{$globals->mail->domain}>");
372 $msg = ($sfemme?'Chère':'Cher')." $sprenom,\n\n"
373 . "Nous t'écrivons pour t'informer que $prenom $nom (X$promo), "
374 . "que tu avais incité".($femme?'e':'')." à s'inscrire à Polytechnique.org, "
375 . "vient à l'instant de terminer son inscription.\n\n"
376 . "Merci de ta participation active à la reconnaissance de ce site !!!\n\n"
377 . "Bien cordialement,\n"
378 . "L'équipe Polytechnique.org";
379 $mymail->setTxtBody(wordwrap($msg, 72));
380 $mymail->send();
381 }
382
383 /**** send a mail to X.org administrators ****/
384 if ($globals->register->notif) {
385 $mymail = new PlMailer();
386 $mymail->setSubject("Inscription de $prenom $nom (X$promo)");
387 $mymail->setFrom('"Webmaster Polytechnique.org" <web@' . $globals->mail->domain . '>');
388 $mymail->addTo($globals->register->notif);
389 $mymail->addHeader('Reply-To', $globals->register->notif);
390 $msg = "$prenom $nom (X$promo) a terminé son inscription avec les données suivantes :\n"
391 . " - nom : $nom\n"
392 . " - prenom : $prenom\n"
393 . " - promo : $promo\n"
394 . " - naissance : $naissance (date connue : $naiss_ini)\n"
395 . " - forlife : $forlife\n"
396 . " - email : $email\n"
397 . " - sexe : $femme\n"
398 . " - ip : " . S::logger()->ip . " (" . S::logger()->host . ")\n"
399 . (S::logger()->proxy_ip ? " - proxy : " . S::logger()->proxy_ip . " (" . S::logger()->proxy_host . ")\n" : "")
400 . "\n\n";
401 if (count($market) > 0) {
402 $msg .= "Les marketings suivants avaient été effectués :\n"
403 . implode("\n", $market);
404 } else {
405 $msg .= "$prenom $nom n'a jamais reçu d'email de marketing.";
406 }
407 $mymail->setTxtBody($msg);
408 $mymail->send();
409 }
410
411 Marketing::clear($uid);
412
413 pl_redirect('register/success');
414 $page->assign('uid', $uid);
415 }
416
417 function handler_success(&$page)
418 {
419 global $globals;
420 $page->changeTpl('register/success.tpl');
421 $page->assign('user', S::user());
422
423 $_SESSION['sub_state'] = array('step' => 5);
424 if (Env::has('response2')) {
425 $_SESSION['password'] = $password = Post::v('response2');
426
427 XDB::execute('UPDATE auth_user_md5 SET password={?}
428 WHERE user_id={?}', $password,
429 S::v('uid'));
430
431 // If GoogleApps is enabled, and the user did choose to use synchronized passwords,
432 // and if the (stupid) user has decided to use /register/success another time,
433 // updates the Google Apps password as well.
434 if ($globals->mailstorage->googleapps_domain) {
435 require_once 'googleapps.inc.php';
436 $account = new GoogleAppsAccount(S::user());
437 if ($account->active() && $account->sync_password) {
438 $account->set_password($password);
439 }
440 }
441
442 S::logger()->log('passwd');
443 Platal::session()->setAccessCookie(true);
444
445 $page->assign('mdpok', true);
446 }
447
448 $res = XDB::iterRow("SELECT sub, domain
449 FROM register_subs
450 WHERE uid = {?} AND type = 'list'
451 ORDER BY domain",
452 S::i('uid'));
453 $current_domain = null;
454 $lists = array();
455 while (list($sub, $domain) = $res->next()) {
456 if ($current_domain != $domain) {
457 $current_domain = $domain;
458 $client = new MMList(S::v('uid'), S::v('password'), $domain);
459 }
460 list($details, ) = $client->get_members($sub);
461 $lists["$sub@$domain"] = $details;
462 }
463 $page->assign_by_ref('lists', $lists);
464
465 $page->addJsLink('motdepasse.js');
466 }
467
468 function handler_save(&$page)
469 {
470 global $globals;
471
472 // Finish registration procedure
473 if (Post::v('register_from_ax_question')) {
474 XDB::execute('UPDATE auth_user_quick
475 SET profile_from_ax = 1
476 WHERE user_id = {?}',
477 S::v('uid'));
478 }
479 if (Post::v('add_to_nl')) {
480 require_once 'newsletter.inc.php';
481 NewsLetter::subscribe();
482 }
483 if (Post::v('add_to_ax')) {
484 Platal::load('axletter', 'axletter.inc.php');
485 AXLetter::subscribe();
486 }
487 if (Post::v('add_to_promo')) {
488 $r = XDB::query('SELECT id FROM groupex.asso WHERE diminutif = {?}',
489 S::v('promo'));
490 $asso_id = $r->fetchOneCell();
491 XDB::execute('REPLACE INTO groupex.membres (uid,asso_id)
492 VALUES ({?}, {?})',
493 S::v('uid'), $asso_id);
494 $mmlist = new MMList(S::v('uid'), S::v('password'));
495 $mmlist->subscribe("promo".S::v('promo'));
496 }
497 if (Post::v('sub_ml')) {
498 $subs = array_keys(Post::v('sub_ml'));
499 $current_domain = null;
500 foreach ($subs as $list) {
501 list($sub, $domain) = explode('@', $list);
502 if ($domain != $current_domain) {
503 $current_domain = $domain;
504 $client = new MMList(S::v('uid'), S::v('password'), $domain);
505 }
506 $client->subscribe($sub);
507 }
508 }
509 if (Post::v('imap')) {
510 require_once 'emails.inc.php';
511 $user = S::user();
512 $storage = new EmailStorage($user, 'imap');
513 $storage->activate();
514 }
515
516 pl_redirect('profile/edit');
517 }
518 }
519
520 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
521 ?>