Integrates email storage backends (IMAP and Google Apps) as almost-normal email redir...
[platal.git] / modules / register.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2008 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 require_once('wiki.inc.php');
87 wiki_require_page('Reference.Charte');
88 if (Post::has('step1')) {
89 $sub_state['step'] = 1;
90 if (isset($sub_state['hash'])) {
91 $sub_state['step'] = 3;
92 require_once(dirname(__FILE__) . '/register/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 require_once(dirname(__FILE__) . '/register/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 require_once(dirname(__FILE__) . '/register/register.inc.php');
140 if (!isvalid_email(Post::v('email'))) {
141 $err[] = "Le champ 'E-mail' n'est pas valide.";
142 } elseif (!isvalid_email_redirection(Post::v('email'))) {
143 $err[] = $sub_state['forlife']." doit renvoyer vers un email existant ".
144 "valide, en particulier, il ne peut pas être renvoyé vers lui-même.";
145 }
146 $birth = trim(Env::v('naissance'));
147 if (!preg_match('@^[0-3]?\d/[01]?\d/(19|20)?\d{2}$@', $birth)) {
148 $err[] = "La 'Date de naissance' n'est pas correcte.";
149 } else {
150 $birth = explode('/', $birth, 3);
151 for ($i = 0; $i < 3; $i++)
152 $birth[$i] = intval($birth[$i]);
153 if ($birth[2] < 100) $birth[2] += 1900;
154 $year = $birth[2];
155 $promo = (int)$sub_state['promo'];
156 if ($year > $promo - 15 || $year < $promo - 30) {
157 $err[] = "La 'Date de naissance' n'est pas correcte.";
158 $alert = "Date de naissance incorrecte a l'inscription - ";
159 $sub_state['wrong_naissance'] = $birth;
160 }
161 }
162
163 // Check if the given email is known as dangerous
164 $res = XDB::query("SELECT w.state, w.description
165 FROM emails_watch AS w
166 WHERE w.email = {?} AND w.state != 'safe'",
167 Post::v('email'));
168 $email_banned = false;
169 if ($res->numRows()) {
170 list($state, $description) = $res->fetchOneRow();
171 $alert .= "Email surveille propose a l'inscription - ";
172 $sub_state['email_desc'] = $description;
173 if ($state == 'dangerous') {
174 $email_banned = true;
175 }
176 }
177 if ($sub_state['watch']) {
178 $alter .= "Inscription d'un utilisateur surveillé - ";
179 }
180
181 if (check_ip('unsafe')) {
182 unset($err);
183 }
184
185 if (isset($err)) {
186 $err = join('<br />', $err);
187 } else {
188 $sub_state['naissance'] = sprintf("%04d-%02d-%02d",
189 intval($birth[2]), intval($birth[1]), intval($birth[0]));
190 if ($sub_state['naissance_ini'] != '0000-00-00' && $sub_state['naissance'] != $sub_state['naissance_ini']) {
191 $alert .= "Date de naissance incorrecte à l'inscription - ";
192 }
193 $sub_state['email'] = Post::v('email');
194 $ip_banned = check_ip('unsafe');
195 if ($ip_banned) {
196 $alert .= "Tentative d'inscription depuis une IP surveillee";
197 }
198 if ($email_banned || $ip_banned) {
199 $err = "Une erreur s'est produite lors de l'inscription."
200 . " Merci de contacter <a href='mailto:register@{$globals->mail->domain}>"
201 . " register@{$globals->mail->domain}</a>"
202 . " pour nous faire part de cette erreur";
203 } else {
204 $sub_state['step'] = 4;
205 if (count($sub_state['backs']) >= 3) {
206 $alert .= "Fin d'une inscription hésitante";
207 }
208 finish_ins($sub_state);
209 }
210 }
211 }
212 break;
213 }
214
215 $_SESSION['sub_state'] = $sub_state;
216 if ($alert) {
217 send_warning_mail($alert);
218 }
219 $page->changeTpl('register/step'.intval($sub_state['step']).'.tpl');
220 if (isset($err)) {
221 $page->trig($err);
222 }
223 }
224
225 function handler_end_old(&$page)
226 {
227 return $this->handler_end($page, Env::v('hash'));
228 }
229
230 function handler_end(&$page, $hash = null)
231 {
232 global $globals;
233
234
235 $page->changeTpl('register/end.tpl');
236 $_SESSION['sub_state'] = array('step' => 5);
237
238 if (check_ip('unsafe')) {
239 send_warning_mail('Une IP surveillée a tenté de finaliser son inscription');
240 XDB::execute('DELETE FROM register_pending
241 WHERE hash = {?} AND hash != \'INSCRIT\'', $hash);
242 return PL_FORBIDDEN;
243 }
244
245 require_once('user.func.inc.php');
246
247 if ($hash) {
248 $res = XDB::query(
249 "SELECT r.uid, r.forlife, r.bestalias, r.mailorg2,
250 r.password, r.email, r.naissance, u.nom, u.prenom,
251 u.promo, FIND_IN_SET('femme', u.flags), u.naissance_ini
252 FROM register_pending AS r
253 INNER JOIN auth_user_md5 AS u ON r.uid = u.user_id
254 WHERE hash={?} AND hash!='INSCRIT'", $hash);
255 }
256
257 if (!$hash || !list($uid, $forlife, $bestalias, $mailorg2, $password, $email,
258 $naissance, $nom, $prenom, $promo, $femme, $naiss_ini) = $res->fetchOneRow())
259 {
260 $page->kill("<p>Cette adresse n'existe pas, ou plus, sur le serveur.</p>
261 <p>Causes probables :</p>
262 <ol>
263 <li>Vérifie que tu visites l'adresse du dernier
264 e-mail reçu s'il y en a eu plusieurs.</li>
265 <li>Tu as peut-être mal copié l'adresse reçue par
266 mail, vérifie-la à la main.</li>
267 <li>Tu as peut-être attendu trop longtemps pour
268 confirmer. Les pré-inscriptions sont annulées
269 tous les 30 jours.</li>
270 <li>Tu es en fait déjà inscrit.</li>
271 </ol>");
272 }
273
274
275
276 /***********************************************************/
277 /****************** REALLY CREATE ACCOUNT ******************/
278 /***********************************************************/
279
280 XDB::execute('UPDATE auth_user_md5
281 SET password={?}, perms="user",
282 date=NOW(), naissance={?}, date_ins = NOW()
283 WHERE user_id={?}', $password, $naissance, $uid);
284 XDB::execute('REPLACE INTO auth_user_quick (user_id) VALUES ({?})', $uid);
285 XDB::execute('INSERT INTO aliases (id,alias,type)
286 VALUES ({?}, {?}, "a_vie")', $uid,
287 $forlife);
288 XDB::execute('INSERT INTO aliases (id,alias,type,flags)
289 VALUES ({?}, {?}, "alias", "bestalias")',
290 $uid, $bestalias);
291 if ($mailorg2) {
292 XDB::execute('INSERT INTO aliases (id,alias,type)
293 VALUES ({?}, {?}, "alias")', $uid,
294 $mailorg2);
295 }
296
297 require_once('emails.inc.php');
298 $redirect = new Redirect($uid);
299 $redirect->add_email($email);
300
301 // on cree un objet logger et on log l'inscription
302 $logger = new CoreLogger($uid);
303 $logger->log('inscription', $email);
304
305 XDB::execute('UPDATE register_pending SET hash="INSCRIT" WHERE uid={?}', $uid);
306
307 global $platal;
308 $platal->on_subscribe($forlife, $uid, $promo, $password);
309
310 $mymail = new PlMailer('register/inscription.reussie.tpl');
311 $mymail->assign('forlife', $forlife);
312 $mymail->assign('prenom', $prenom);
313 $mymail->send();
314
315 require_once('user.func.inc.php');
316 user_reindex($uid);
317
318 // update number of subscribers (perms has changed)
319 update_NbIns();
320
321 if (!start_connexion($uid, false)) {
322 return PL_FORBIDDEN;
323 }
324 $_SESSION['auth'] = AUTH_MDP;
325
326 /***********************************************************/
327 /************* envoi d'un mail au démarcheur ***************/
328 /***********************************************************/
329 $res = XDB::iterRow(
330 "SELECT sa.alias, IF(s.nom_usage,s.nom_usage,s.nom) AS nom,
331 s.prenom, FIND_IN_SET('femme', s.flags) AS femme,
332 GROUP_CONCAT(m.email) AS mails, MAX(m.last) AS dateDernier
333 FROM register_marketing AS m
334 INNER JOIN auth_user_md5 AS s ON ( m.sender = s.user_id )
335 INNER JOIN aliases AS sa ON ( sa.id = m.sender
336 AND FIND_IN_SET('bestalias', sa.flags) )
337 WHERE m.uid = {?}
338 GROUP BY m.sender", $uid);
339 XDB::execute("UPDATE register_mstats SET success=NOW() WHERE uid={?}", $uid);
340
341 $market = array();
342 while (list($salias, $snom, $sprenom, $sfemme, $mails, $dateDernier) = $res->next()) {
343 $market[] = " - par $snom $sprenom sur $mails (le plus récemment le $dateDernier)";
344 $mymail = new PlMailer();
345 $mymail->setSubject("$prenom $nom s'est inscrit à Polytechnique.org !");
346 $mymail->setFrom('"Marketing Polytechnique.org" <register@' . $globals->mail->domain . '>');
347 $mymail->addTo("\"$sprenom $snom\" <$salias@{$globals->mail->domain}>");
348 $msg = ($sfemme?'Chère':'Cher')." $sprenom,\n\n"
349 . "Nous t'écrivons pour t'informer que $prenom $nom (X$promo), "
350 . "que tu avais incité".($femme?'e':'')." à s'inscrire à Polytechnique.org, "
351 . "vient à l'instant de terminer son inscription.\n\n"
352 . "Merci de ta participation active à la reconnaissance de ce site !!!\n\n"
353 . "Bien cordialement,\n"
354 . "L'équipe Polytechnique.org";
355 $mymail->setTxtBody(wordwrap($msg, 72));
356 $mymail->send();
357 }
358
359 /**** send a mail to X.org administrators ****/
360 if ($globals->register->notif) {
361 $mymail = new PlMailer();
362 $mymail->setSubject("Inscription de $prenom $nom (X$promo)");
363 $mymail->setFrom('"Webmaster Polytechnique.org" <web@' . $globals->mail->domain . '>');
364 $mymail->addTo($globals->register->notif);
365 $msg = "$prenom $nom (X$promo) a terminé son inscription avec les données suivantes :\n"
366 . " - nom : $nom\n"
367 . " - prenom : $prenom\n"
368 . " - promo : $promo\n"
369 . " - naissance : $naissance (date connue : $naiss_ini)\n"
370 . " - forlife : $forlife\n"
371 . " - email : $email\n"
372 . " - sexe : $femme\n"
373 . " - ip : {$logger->ip} ({$logger->host})\n"
374 . ($logger->proxy_ip ? " - proxy : {$logger->proxy_ip} ({$logger->proxy_host})\n" : "")
375 . "\n\n"
376 . "Les marketings suivants avaient été effectués :\n"
377 . implode("\n", $market);
378 $mymail->setTxtBody($msg);
379 $mymail->send();
380 }
381
382 Marketing::clear($uid);
383
384 pl_redirect('register/success');
385 $page->assign('uid', $uid);
386 }
387
388 function handler_success(&$page)
389 {
390 global $globals;
391 $page->changeTpl('register/success.tpl');
392
393 $_SESSION['sub_state'] = array('step' => 5);
394 if (Env::has('response2')) {
395 $_SESSION['password'] = $password = Post::v('response2');
396
397 XDB::execute('UPDATE auth_user_md5 SET password={?}
398 WHERE user_id={?}', $password,
399 S::v('uid'));
400
401 // If GoogleApps is enabled, and the user did choose to use synchronized passwords,
402 // and if the (stupid) user has decided to user /register/success another time,
403 // updates the Google Apps password as well.
404 if ($globals->mailstorage->googleapps_domain) {
405 require_once 'googleapps.inc.php';
406 $account = new GoogleAppsAccount(S::v('uid'), S::v('forlife'));
407 if ($account->active() && $account->sync_password) {
408 $account->set_password($password);
409 }
410 }
411
412 $log = S::v('log');
413 $log->log('passwd', '');
414
415 if (Cookie::v('ORGaccess')) {
416 require_once('secure_hash.inc.php');
417 setcookie('ORGaccess', hash_encrypt($password), (time()+25920000), '/', '' ,0);
418 }
419
420 $page->assign('mdpok', true);
421 }
422
423 $res = XDB::iterRow("SELECT sub, domain
424 FROM register_subs
425 WHERE uid = {?} AND type = 'list'
426 ORDER BY domain",
427 S::i('uid'));
428 $current_domain = null;
429 $lists = array();
430 while (list($sub, $domain) = $res->next()) {
431 if ($current_domain != $domain) {
432 $current_domain = $domain;
433 $client = new MMList(S::v('uid'), S::v('password'), $domain);
434 }
435 list($details, ) = $client->get_members($sub);
436 $lists["$sub@$domain"] = $details;
437 }
438 $page->assign_by_ref('lists', $lists);
439
440 $page->addJsLink('motdepasse.js');
441 }
442
443 function handler_save(&$page)
444 {
445 global $globals;
446
447 // Finish registration procedure
448 if (Post::v('register_from_ax_question')) {
449 XDB::execute('UPDATE auth_user_quick
450 SET profile_from_ax = 1
451 WHERE user_id = {?}',
452 S::v('uid'));
453 }
454 if (Post::v('add_to_nl')) {
455 require_once 'newsletter.inc.php';
456 NewsLetter::subscribe();
457 }
458 if (Post::v('add_to_ax')) {
459 require_once dirname(__FILE__) . '/axletter/axletter.inc.php';
460 AXLetter::subscribe();
461 }
462 if (Post::v('add_to_promo')) {
463 $r = XDB::query('SELECT id FROM groupex.asso WHERE diminutif = {?}',
464 S::v('promo'));
465 $asso_id = $r->fetchOneCell();
466 XDB::execute('REPLACE INTO groupex.membres (uid,asso_id)
467 VALUES ({?}, {?})',
468 S::v('uid'), $asso_id);
469 $mmlist = new MMList(S::v('uid'), S::v('password'));
470 $mmlist->subscribe("promo".S::v('promo'));
471 }
472 if (Post::v('sub_ml')) {
473 $subs = array_keys(Post::v('sub_ml'));
474 $current_domain = null;
475 foreach ($subs as $list) {
476 list($sub, $domain) = explode('@', $list);
477 if ($domain != $current_domain) {
478 $current_domain = $domain;
479 $client = new MMList(S::v('uid'), S::v('password'), $domain);
480 }
481 $client->subscribe($sub);
482 }
483 }
484 if (Post::v('imap')) {
485 require_once 'emails.inc.php';
486 $storage = new EmailStorage(S::v('uid'), 'imap');
487 $storage->enable();
488 }
489
490 pl_redirect('profile/edit');
491 }
492 }
493
494 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
495 ?>