Fixes a SQL query in modules/axletter/axletter.inc.php.
[platal.git] / modules / email.php
CommitLineData
81b5b746 1<?php
2/***************************************************************************
8d84c630 3 * Copyright (C) 2003-2009 Polytechnique.org *
81b5b746 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
22class EmailModule extends PLModule
23{
81b5b746 24 function handlers()
25 {
26 return array(
eb5a266d
SJ
27 'emails' => $this->make_hook('emails', AUTH_COOKIE),
28 'emails/alias' => $this->make_hook('alias', AUTH_MDP),
29 'emails/antispam' => $this->make_hook('antispam', AUTH_MDP),
30 'emails/broken' => $this->make_hook('broken', AUTH_COOKIE),
31 'emails/redirect' => $this->make_hook('redirect', AUTH_MDP),
32 'emails/send' => $this->make_hook('send', AUTH_MDP),
33 'emails/antispam/submit' => $this->make_hook('submit', AUTH_COOKIE),
34 'emails/test' => $this->make_hook('test', AUTH_COOKIE, 'user', NO_AUTH),
9e570fe0 35
eb5a266d
SJ
36 'emails/rewrite/in' => $this->make_hook('rewrite_in', AUTH_PUBLIC),
37 'emails/rewrite/out' => $this->make_hook('rewrite_out', AUTH_PUBLIC),
3d17e48f 38
eb5a266d 39 'emails/imap/in' => $this->make_hook('imap_in', AUTH_PUBLIC),
2ee43273 40
eb5a266d
SJ
41 'admin/emails/duplicated' => $this->make_hook('duplicated', AUTH_MDP, 'admin'),
42 'admin/emails/watch' => $this->make_hook('duplicated', AUTH_MDP, 'admin'),
43 'admin/emails/lost' => $this->make_hook('lost', AUTH_MDP, 'admin'),
81b5b746 44 );
45 }
46
b7582015 47 function handler_emails(&$page, $action = null, $email = null)
81b5b746 48 {
49 global $globals;
e97e9b8f 50 require_once 'emails.inc.php';
81b5b746 51
52 $page->changeTpl('emails/index.tpl');
46f272fe 53 $page->setTitle('Mes emails');
81b5b746 54
2d997414 55 $user = S::user();
81b5b746 56
2d997414 57 // Apply the bestalias change request.
b7582015 58 if ($action == 'best' && $email) {
46504fb3
VZ
59 if (!S::has_xsrf_token()) {
60 return PL_FORBIDDEN;
61 }
62
2d997414
VZ
63 XDB::execute("UPDATE aliases
64 SET flags = TRIM(BOTH ',' FROM REPLACE(CONCAT(',', flags, ','), ',bestalias,', ','))
65 WHERE id = {?}", $user->id());
66 XDB::execute("UPDATE aliases
67 SET flags = CONCAT_WS(',', IF(flags = '', NULL, flags), 'bestalias')
68 WHERE id = {?} AND alias = {?}", $user->id(), $email);
69
70 // As having a non-null bestalias value is critical in
71 // plat/al's code, we do an a posteriori check on the
72 // validity of the bestalias.
73 fix_bestalias($user);
81b5b746 74 }
75
2d997414 76 // Fetch and display aliases.
81b5b746 77 $sql = "SELECT alias, (type='a_vie') AS a_vie,
78 (alias REGEXP '\\\\.[0-9]{2}$') AS cent_ans,
79 FIND_IN_SET('bestalias',flags) AS best, expire
80 FROM aliases
81 WHERE id = {?} AND type!='homonyme'
82 ORDER BY LENGTH(alias)";
2d997414 83 $page->assign('aliases', XDB::iterator($sql, $user->id()));
81b5b746 84
2d997414
VZ
85 // Check for homonyms.
86 $homonyme = XDB::query(
87 "SELECT alias
88 FROM aliases
89 INNER JOIN homonymes ON (id = homonyme_id)
90 WHERE user_id = {?} AND type = 'homonyme'", $user->id());
e97e9b8f 91 $page->assign('homonyme', $homonyme->fetchOneCell());
e1547442 92
2d997414
VZ
93 // Display active redirections.
94 $redirect = new Redirect($user);
e97e9b8f 95 $page->assign('mails', $redirect->active_emails());
81b5b746 96
2d997414 97 // Display, when available, the @alias_dom email alias.
08cce2ff 98 $res = XDB::query(
81b5b746 99 "SELECT alias
100 FROM virtual AS v
101 INNER JOIN virtual_redirect AS vr USING(vid)
eaf30d86 102 WHERE (redirect={?} OR redirect={?})
81b5b746 103 AND alias LIKE '%@{$globals->mail->alias_dom}'",
2d997414
VZ
104 $user->forlifeEmail(),
105 // TODO: remove this über-ugly hack. The issue is that you need
106 // to remove all @m4x.org addresses in virtual_redirect first.
107 $user->login() . '@' . $globals->mail->domain2);
81b5b746 108 $page->assign('melix', $res->fetchOneCell());
81b5b746 109 }
110
111 function handler_alias(&$page, $action = null, $value = null)
112 {
113 require_once 'validations.inc.php';
114
115 global $globals;
116
117 $page->changeTpl('emails/alias.tpl');
46f272fe 118 $page->setTitle('Alias melix.net');
81b5b746 119
2d997414
VZ
120 $user = S::user();
121 $page->assign('demande', AliasReq::get_request($user->id()));
81b5b746 122
2d997414 123 // Remove the email alias.
40d428d8
VZ
124 if ($action == 'delete' && $value) {
125 S::assert_xsrf_token();
126
08cce2ff 127 XDB::execute(
2d997414
VZ
128 "DELETE virtual, virtual_redirect
129 FROM virtual
130 INNER JOIN virtual_redirect USING (vid)
131 WHERE alias = {?} AND (redirect = {?} OR redirect = {?})",
132 $value, $user->forlifeEmail(),
133 // TODO: remove this über-ugly hack. The issue is that you need
134 // to remove all @m4x.org addresses in virtual_redirect first.
135 $user->login() . '@' . $globals->mail->domain2);
81b5b746 136 }
137
2d997414 138 // Fetch existing @alias_dom aliases.
08cce2ff 139 $res = XDB::query(
81b5b746 140 "SELECT alias, emails_alias_pub
141 FROM auth_user_quick, virtual
142 INNER JOIN virtual_redirect USING(vid)
2d997414 143 WHERE (redirect = {?} OR redirect = {?})
eaf30d86 144 AND alias LIKE '%@{$globals->mail->alias_dom}' AND user_id = {?}",
2d997414
VZ
145 $user->forlifeEmail(),
146 // TODO: remove this über-ugly hack. The issue is that you need
147 // to remove all @m4x.org addresses in virtual_redirect first.
148 $user->login() . '@' . $globals->mail->domain2, $user->id());
81b5b746 149 list($alias, $visibility) = $res->fetchOneRow();
150 $page->assign('actuel', $alias);
151
40d428d8
VZ
152 if ($action == 'ask' && Env::has('alias') && Env::has('raison')) {
153 S::assert_xsrf_token();
81b5b746 154
40d428d8 155 //Si l'utilisateur vient de faire une damande
5e2307dc 156 $alias = Env::v('alias');
157 $raison = Env::v('raison');
158 $public = (Env::v('public', 'off') == 'on')?"public":"private";
81b5b746 159
160 $page->assign('r_alias', $alias);
161 $page->assign('r_raison', $raison);
162 if ($public == 'public') {
163 $page->assign('r_public', true);
164 }
165
a7de4ef7 166 //Quelques vérifications sur l'alias (caractères spéciaux)
81b5b746 167 if (!preg_match( "/^[a-zA-Z0-9\-.]{3,20}$/", $alias)) {
a7d35093
FB
168 $page->trigError("L'adresse demandée n'est pas valide."
169 . " Vérifie qu'elle comporte entre 3 et 20 caractères"
170 . " et qu'elle ne contient que des lettres non accentuées,"
171 . " des chiffres ou les caractères - et .");
fd8f77de 172 return;
81b5b746 173 } else {
a7de4ef7 174 //vérifier que l'alias n'est pas déja pris
08cce2ff 175 $res = XDB::query('SELECT COUNT(*) FROM virtual WHERE alias={?}',
81b5b746 176 $alias.'@'.$globals->mail->alias_dom);
177 if ($res->fetchOneCell() > 0) {
a7d35093 178 $page->trigError("L'alias $alias@{$globals->mail->alias_dom} a déja été attribué.
81b5b746 179 Tu ne peux donc pas l'obtenir.");
fd8f77de 180 return;
81b5b746 181 }
182
a7de4ef7 183 //vérifier que l'alias n'est pas déja en demande
81b5b746 184 $it = new ValidateIterator ();
185 while($req = $it->next()) {
1f07f6c2 186 if ($req->type == "alias" and $req->alias == $alias . '@' . $globals->mail->alias_dom) {
a7d35093 187 $page->trigError("L'alias $alias@{$globals->mail->alias_dom} a déja été demandé.
81b5b746 188 Tu ne peux donc pas l'obtenir pour l'instant.");
fd8f77de 189 return ;
81b5b746 190 }
191 }
192
a7de4ef7 193 //Insertion de la demande dans la base, écrase les requêtes précédente
2d997414 194 $myalias = new AliasReq($user, $alias, $raison, $public);
81b5b746 195 $myalias->submit();
196 $page->assign('success',$alias);
fd8f77de 197 return;
81b5b746 198 }
46504fb3
VZ
199 } elseif ($action == 'set' && ($value == 'public' || $value == 'private')) {
200 if (!S::has_xsrf_token()) {
201 return PL_FORBIDDEN;
202 }
203
81b5b746 204 if ($value == 'public') {
08cce2ff 205 XDB::execute("UPDATE auth_user_quick SET emails_alias_pub = 'public'
2d997414 206 WHERE user_id = {?}", $user->id());
81b5b746 207 } else {
08cce2ff 208 XDB::execute("UPDATE auth_user_quick SET emails_alias_pub = 'private'
2d997414 209 WHERE user_id = {?}", $user->id());
81b5b746 210 }
211
212 $visibility = $value;
213 }
214
215 $page->assign('mail_public', ($visibility == 'public'));
81b5b746 216 }
217
218 function handler_redirect(&$page, $action = null, $email = null)
219 {
220 global $globals;
221
222 require_once 'emails.inc.php';
223
224 $page->changeTpl('emails/redirect.tpl');
225
2d997414
VZ
226 $user = S::user();
227 $page->assign_by_ref('user', $user);
228 $page->assign('eleve', $user->promo() >= date("Y") - 5);
3b83212e 229
2d997414 230 $redirect = new Redirect($user);
81b5b746 231
6d6b65bf 232 // FS#703 : $_GET is urldecoded twice, hence
233 // + (the data) => %2B (in the url) => + (first decoding) => ' ' (second decoding)
234 // Since there can be no spaces in emails, we can fix this with :
235 $email = str_replace(' ', '+', $email);
236
2d997414 237 // Apply email redirection change requests.
1060c854 238 $result = SUCCESS;
81b5b746 239 if ($action == 'remove' && $email) {
1060c854 240 $result = $redirect->delete_email($email);
81b5b746 241 }
e1547442
FB
242
243 if ($action == 'active' && $email) {
244 $redirect->modify_one_email($email, true);
245 }
246
247 if ($action == 'inactive' && $email) {
248 $redirect->modify_one_email($email, false);
249 }
250
251 if ($action == 'rewrite' && $email) {
252 $rewrite = @func_get_arg(3);
253 $redirect->modify_one_email_redirect($email, $rewrite);
254 }
255
40d428d8
VZ
256 if (Env::has('emailop')) {
257 S::assert_xsrf_token();
258
5e2307dc 259 $actifs = Env::v('emails_actifs', Array());
b7582015 260 print_r(Env::v('emails_rewrite'));
5e2307dc 261 if (Env::v('emailop') == "ajouter" && Env::has('email')) {
1060c854 262 $result = $redirect->add_email(Env::v('email'));
81b5b746 263 } elseif (empty($actifs)) {
1060c854 264 $result = ERROR_INACTIVE_REDIRECTION;
81b5b746 265 } elseif (is_array($actifs)) {
1060c854 266 $result = $redirect->modify_email($actifs, Env::v('emails_rewrite', Array()));
81b5b746 267 }
268 }
269
1060c854 270 switch ($result) {
44b071c2
SJ
271 case ERROR_INACTIVE_REDIRECTION:
272 $page->trigError('Tu ne peux pas avoir aucune adresse de redirection active, sinon ton adresse '
4478f95e 273 . $user->forlifeEmail() . ' ne fonctionnerait plus.');
44b071c2
SJ
274 break;
275 case ERROR_INVALID_EMAIL:
276 $page->trigError('Erreur: l\'email n\'est pas valide.');
277 break;
278 case ERROR_LOOP_EMAIL:
4478f95e 279 $page->trigError('Erreur : ' . $user->forlifeEmail()
44b071c2
SJ
280 . ' ne doit pas être renvoyé vers lui-même, ni vers son équivalent en '
281 . $globals->mail->domain2 . ' ni vers polytechnique.edu.');
282 break;
283 }
284
2d997414 285 // Fetch the @alias_dom email alias, if any.
08cce2ff 286 $res = XDB::query(
81b5b746 287 "SELECT alias
288 FROM virtual
289 INNER JOIN virtual_redirect USING(vid)
290 WHERE (redirect={?} OR redirect={?})
eaf30d86 291 AND alias LIKE '%@{$globals->mail->alias_dom}'",
2d997414
VZ
292 $user->forlifeEmail(),
293 // TODO: remove this über-ugly hack. The issue is that you need
294 // to remove all @m4x.org addresses in virtual_redirect first.
295 $user->login() . '@' . $globals->mail->domain2);
81b5b746 296 $melix = $res->fetchOneCell();
297 if ($melix) {
298 list($melix) = explode('@', $melix);
299 $page->assign('melix',$melix);
300 }
301
2d997414 302 // Fetch existing email aliases.
08cce2ff 303 $res = XDB::query(
81b5b746 304 "SELECT alias,expire
305 FROM aliases
306 WHERE id={?} AND (type='a_vie' OR type='alias')
2d997414 307 ORDER BY !FIND_IN_SET('usage',flags), LENGTH(alias)", $user->id());
81b5b746 308 $page->assign('alias', $res->fetchAllAssoc());
2d997414 309 $page->assign('emails', $redirect->emails);
aab4661d 310
2d997414 311 // Display GoogleApps acount information.
f5c4bf30 312 require_once 'googleapps.inc.php';
2d997414 313 $page->assign('googleapps', GoogleAppsAccount::account_status($user->id()));
81b5b746 314 }
315
b7582015 316 function handler_antispam(&$page, $statut_filtre = null)
81b5b746 317 {
318 require_once 'emails.inc.php';
8f201b69
FB
319 $wp = new PlWikiPage('Xorg.Antispam');
320 $wp->buildCache();
81b5b746 321
322 $page->changeTpl('emails/antispam.tpl');
323
12a587df 324 $bogo = new Bogo(S::user());
b7582015 325 if (isset($statut_filtre)) {
11ed26e5 326 $bogo->change($statut_filtre + 0);
81b5b746 327 }
2d997414 328 $page->assign('filtre', $bogo->level());
81b5b746 329 }
330
62ce6356 331 function handler_submit(&$page)
332 {
8f201b69
FB
333 $wp = new PlWikiPage('Xorg.Mails');
334 $wp->buildCache();
62ce6356 335 $page->changeTpl('emails/submit_spam.tpl');
336
40d428d8
VZ
337 if (Post::has('send_email')) {
338 S::assert_xsrf_token();
339
f3df6d38 340 $upload = PlUpload::get($_FILES['mail'], S::user()->login(), 'spam.submit', true);
15603084 341 if (!$upload) {
a7d35093 342 $page->trigError('Une erreur a été rencontrée lors du transfert du fichier');
62ce6356 343 return;
344 }
15603084 345 $mime = $upload->contentType();
62ce6356 346 if ($mime != 'text/x-mail' && $mime != 'message/rfc822') {
15603084 347 $upload->clear();
faefdbb7 348 $page->trigError('Le fichier ne contient pas un email complet');
62ce6356 349 return;
350 }
2d997414
VZ
351 $type = (Post::v('type') == 'spam' ? 'spam' : 'nonspam');
352
62ce6356 353 global $globals;
2d997414 354 $box = $type . '@' . $globals->mail->domain;
62ce6356 355 $mailer = new PlMailer();
356 $mailer->addTo($box);
2d997414
VZ
357 $mailer->setFrom('"' . S::user()->fullName() . '" <web@' . $globals->mail->domain . '>');
358 $mailer->setTxtBody($type . ' soumis par ' . S::user()->login() . ' via le web');
359 $mailer->addUploadAttachment($upload, $type . '.mail');
62ce6356 360 $mailer->send();
a7d35093 361 $page->trigSuccess('Le message a été transmis à ' . $box);
15603084 362 $upload->clear();
62ce6356 363 }
364 }
365
81b5b746 366 function handler_send(&$page)
367 {
81b5b746 368 $page->changeTpl('emails/send.tpl');
da419622 369 $page->addJsLink('ajax.js');
81b5b746 370
46f272fe 371 $page->setTitle('Envoyer un email');
81b5b746 372
373 // action si on recoit un formulaire
3360c04f 374 if (Post::has('save')) {
46504fb3
VZ
375 if (!S::has_xsrf_token()) {
376 return PL_FORBIDDEN;
377 }
378
3360c04f
FB
379 unset($_POST['save']);
380 if (trim(preg_replace('/-- .*/', '', Post::v('contenu'))) != "") {
381 $_POST['to_contacts'] = explode(';', @$_POST['to_contacts']);
382 $_POST['cc_contacts'] = explode(';', @$_POST['cc_contacts']);
383 $data = serialize($_POST);
384 XDB::execute("REPLACE INTO email_send_save
385 VALUES ({?}, {?})", S::i('uid'), $data);
386 }
387 exit;
40d428d8
VZ
388 } else if (Env::v('submit') == 'Envoyer') {
389 S::assert_xsrf_token();
390
91a14f73 391 function getEmails($aliases)
392 {
393 if (!is_array($aliases)) {
394 return null;
395 }
396 $rel = Env::v('contacts');
397 $ret = array();
398 foreach ($aliases as $alias) {
399 $ret[$alias] = $rel[$alias];
400 }
401 return join(', ', $ret);
402 }
403
5e68682e 404 $error = false;
da419622 405 foreach ($_FILES as &$file) {
f3df6d38 406 if ($file['name'] && !PlUpload::get($file, S::user()->login(), 'emails.send', false)) {
a7d35093 407 $page->trigError(PlUpload::$lastError);
5e68682e
FB
408 $error = true;
409 break;
da419622 410 }
411 }
412
5e68682e
FB
413 if (!$error) {
414 XDB::execute("DELETE FROM email_send_save
415 WHERE uid = {?}", S::i('uid'));
416
417 $to2 = getEmails(Env::v('to_contacts'));
418 $cc2 = getEmails(Env::v('cc_contacts'));
419 $txt = str_replace('^M', '', Env::v('contenu'));
420 $to = Env::v('to');
421 $subj = Env::v('sujet');
422 $from = Env::v('from');
423 $cc = trim(Env::v('cc'));
424 $bcc = trim(Env::v('bcc'));
425
426 if (empty($to) && empty($cc) && empty($to2) && empty($bcc) && empty($cc2)) {
a7d35093 427 $page->trigError("Indique au moins un destinataire.");
f3df6d38 428 $page->assign('uploaded_f', PlUpload::listFilenames(S::user()->login(), 'emails.send'));
5e68682e
FB
429 } else {
430 $mymail = new PlMailer();
431 $mymail->setFrom($from);
432 $mymail->setSubject($subj);
433 if (!empty($to)) { $mymail->addTo($to); }
434 if (!empty($cc)) { $mymail->addCc($cc); }
435 if (!empty($bcc)) { $mymail->addBcc($bcc); }
436 if (!empty($to2)) { $mymail->addTo($to2); }
437 if (!empty($cc2)) { $mymail->addCc($cc2); }
f3df6d38 438 $files =& PlUpload::listFiles(S::user()->login(), 'emails.send');
5e68682e
FB
439 foreach ($files as $name=>&$upload) {
440 $mymail->addUploadAttachment($upload, $name);
441 }
442 if (Env::v('nowiki')) {
443 $mymail->setTxtBody(wordwrap($txt, 78, "\n"));
444 } else {
445 $mymail->setWikiBody($txt);
446 }
447 if ($mymail->send()) {
faefdbb7 448 $page->trigSuccess("Ton email a bien été envoyé.");
2d997414 449 $_REQUEST = array('bcc' => S::user()->bestEmail());
f3df6d38 450 PlUpload::clear(S::user()->login(), 'emails.send');
5e68682e 451 } else {
a7d35093 452 $page->trigError("Erreur lors de l'envoi du courriel, réessaye.");
f3df6d38 453 $page->assign('uploaded_f', PlUpload::listFilenames(S::user()->login(), 'emails.send'));
5e68682e 454 }
81b5b746 455 }
456 }
457 } else {
3360c04f
FB
458 $res = XDB::query("SELECT data
459 FROM email_send_save
460 WHERE uid = {?}", S::i('uid'));
461 if ($res->numRows() == 0) {
f3df6d38 462 PlUpload::clear(S::user()->login(), 'emails.send');
2d997414 463 $_REQUEST['bcc'] = S::user()->bestEmail();
3360c04f
FB
464 } else {
465 $data = unserialize($res->fetchOneCell());
466 $_REQUEST = array_merge($_REQUEST, $data);
467 }
81b5b746 468 }
469
08cce2ff 470 $res = XDB::query(
81b5b746 471 "SELECT u.prenom, u.nom, u.promo, a.alias as forlife
472 FROM auth_user_md5 AS u
473 INNER JOIN contacts AS c ON (u.user_id = c.contact)
474 INNER JOIN aliases AS a ON (u.user_id=a.id AND FIND_IN_SET('bestalias',a.flags))
475 WHERE c.uid = {?}
cab08090 476 ORDER BY u.nom, u.prenom", S::v('uid'));
81b5b746 477 $page->assign('contacts', $res->fetchAllAssoc());
5e68682e 478 $page->assign('maxsize', ini_get('upload_max_filesize') . 'o');
2d997414 479 $page->assign('user', S::user());
81b5b746 480 }
481
d0c3e04d 482 function handler_test(&$page, $hruid = null)
5ff3f06b 483 {
e4ecada4
VZ
484 require_once 'emails.inc.php';
485
46504fb3
VZ
486 if (!S::has_xsrf_token()) {
487 return PL_FORBIDDEN;
488 }
d0c3e04d
VZ
489
490 // Retrieves the User object for the test email recipient.
491 if (S::has_perms() && $hruid) {
492 $user = User::getSilent($hruid);
493 } else {
494 $user = S::user();
495 }
496 if (!$user) {
497 return PL_NOT_FOUND;
5ff3f06b 498 }
e4ecada4 499
d0c3e04d 500 // Sends the test email.
12a587df 501 $redirect = new Redirect($user);
e4ecada4
VZ
502
503 $mailer = new PlMailer('emails/test.mail.tpl');
d0c3e04d 504 $mailer->assign('email', $user->bestEmail());
e4ecada4 505 $mailer->assign('redirects', $redirect->active_emails());
d0c3e04d
VZ
506 $mailer->assign('display_name', $user->displayName());
507 $mailer->assign('sexe', $user->isFemale());
508 $mailer->send($user->isEmailFormatHtml());
5ff3f06b
FB
509 exit;
510 }
511
3d17e48f
FB
512 function handler_rewrite_in(&$page, $mail, $hash)
513 {
514 $page->changeTpl('emails/rewrite.tpl');
515 $page->assign('option', 'in');
516 if (empty($mail) || empty($hash)) {
517 return PL_NOT_FOUND;
518 }
519 $pos = strrpos($mail, '_');
520 if ($pos === false) {
521 return PL_NOT_FOUND;
522 }
523 $mail{$pos} = '@';
524 $res = XDB::query("SELECT COUNT(*)
525 FROM emails
526 WHERE email = {?} AND hash = {?}",
527 $mail, $hash);
528 $count = intval($res->fetchOneCell());
529 if ($count > 0) {
530 XDB::query("UPDATE emails
531 SET allow_rewrite = true, hash = NULL
532 WHERE email = {?} AND hash = {?}",
533 $mail, $hash);
534 $page->trigSuccess("Réécriture activée pour l'adresse " . $mail);
535 return;
536 }
537 return PL_NOT_FOUND;
538 }
539
540 function handler_rewrite_out(&$page, $mail, $hash)
541 {
542 $page->changeTpl('emails/rewrite.tpl');
543 $page->assign('option', 'out');
544 if (empty($mail) || empty($hash)) {
545 return PL_NOT_FOUND;
546 }
547 $pos = strrpos($mail, '_');
548 if ($pos === false) {
549 return PL_NOT_FOUND;
550 }
551 $mail{$pos} = '@';
552 $res = XDB::query("SELECT COUNT(*)
553 FROM emails
554 WHERE email = {?} AND hash = {?}",
555 $mail, $hash);
556 $count = intval($res->fetchOneCell());
557 if ($count > 0) {
558 global $globals;
559 $res = XDB::query("SELECT e.email, e.rewrite, a.alias
560 FROM emails AS e
561 INNER JOIN aliases AS a ON (a.id = e.uid AND a.type = 'a_vie')
562 WHERE e.email = {?} AND e.hash = {?}",
563 $mail, $hash);
564 XDB::query("UPDATE emails
565 SET allow_rewrite = false, hash = NULL
566 WHERE email = {?} AND hash = {?}",
567 $mail, $hash);
568 list($mail, $rewrite, $forlife) = $res->fetchOneRow();
569 $mail = new PlMailer();
570 $mail->setFrom("webmaster@" . $globals->mail->domain);
571 $mail->addTo("support@" . $globals->mail->domain);
572 $mail->setSubject("Tentative de détournement de correspondance via le rewrite");
573 $mail->setTxtBody("$forlife a tenté un rewrite de $mail vers $rewrite. Cette demande a été rejetée via le web");
574 $mail->send();
575 $page->trigWarning("Un mail d'alerte a été envoyé à l'équipe de " . $globals->core->sitename);
576 return;
577 }
578 return PL_NOT_FOUND;
579 }
580
2ee43273
FB
581 function handler_imap_in(&$page, $hash = null, $login = null)
582 {
583 $page->changeTpl('emails/imap_register.tpl');
12a587df 584 $user = null;
2ee43273 585 if (!empty($hash) || !empty($login)) {
12a587df
VZ
586 $user = User::getSilent($login);
587 if ($user) {
588 $req = XDB::query("SELECT 1 FROM newsletter_ins WHERE user_id = {?} AND hash = {?}", $user->id(), $hash);
589 if ($req->numRows() == 0) {
590 $user = null;
591 }
592 }
2ee43273
FB
593 }
594
595 require_once('emails.inc.php');
596 $page->assign('ok', false);
12a587df
VZ
597 if (S::logged() && (is_null($user) || $user->id() == S::i('uid'))) {
598 $storage = new EmailStorage(S::user(), 'imap');
2ee43273
FB
599 $storage->activate();
600 $page->assign('ok', true);
601 $page->assign('prenom', S::v('prenom'));
e2cea47d 602 $page->assign('sexe', S::v('femme'));
12a587df
VZ
603 } else if (!S::logged() && $user) {
604 $storage = new EmailStorage($user, 'imap');
2ee43273
FB
605 $storage->activate();
606 $page->assign('ok', true);
12a587df
VZ
607 $page->assign('prenom', $user->displayName());
608 $page->assign('sexe', $user->isFemale());
2ee43273
FB
609 }
610 }
611
81b5b746 612 function handler_broken(&$page, $warn = null, $email = null)
613 {
614 require_once 'emails.inc.php';
8f201b69
FB
615 $wp = new PlWikiPage('Xorg.PatteCassée');
616 $wp->buildCache();
81b5b746 617
618 global $globals;
619
620 $page->changeTpl('emails/broken.tpl');
621
40d428d8
VZ
622 if ($warn == 'warn' && $email) {
623 S::assert_xsrf_token();
624
81b5b746 625 $email = valide_email($email);
a7de4ef7 626 // vérifications d'usage
2d997414
VZ
627 $sel = XDB::query("SELECT uid FROM emails WHERE email = {?}", $email);
628 if (($uid = $sel->fetchOneCell())) {
629 $dest = User::getSilent($uid);
630
81b5b746 631 // envoi du mail
632 $message = "Bonjour !
633
faefdbb7 634Cet email a été généré automatiquement par le service de patte cassée de
2d997414 635Polytechnique.org car un autre utilisateur, " . S::user()->fullName() . ",
faefdbb7 636nous a signalé qu'en t'envoyant un email, il avait reçu un message d'erreur
81b5b746 637indiquant que ton adresse de redirection $email
638ne fonctionnait plus !
639
a7de4ef7 640Nous te suggérons de vérifier cette adresse, et le cas échéant de mettre
641à jour sur le site <{$globals->baseurl}/emails> tes adresses
81b5b746 642de redirection...
643
661e78f7 644Pour plus de renseignements sur le service de patte cassée, n'hésite pas à
2c388954 645consulter la page <{$globals->baseurl}/emails/broken>.
81b5b746 646
647
661e78f7 648À bientôt sur Polytechnique.org !
1d55fe45 649L'équipe d'administration <support@" . $globals->mail->domain . '>';
81b5b746 650
1e33266a 651 $mail = new PlMailer();
1d55fe45 652 $mail->setFrom('"Polytechnique.org" <support@' . $globals->mail->domain . '>');
2d997414 653 $mail->addTo($dest->bestEmail());
81b5b746 654 $mail->setSubject("Une de tes adresse de redirection Polytechnique.org ne marche plus !!");
655 $mail->setTxtBody($message);
656 $mail->send();
faefdbb7 657 $page->trigSuccess("Email envoyé !");
81b5b746 658 }
40d428d8
VZ
659 } elseif (Post::has('email')) {
660 S::assert_xsrf_token();
661
5e2307dc 662 $email = valide_email(Post::v('email'));
81b5b746 663
664 list(,$fqdn) = explode('@', $email);
665 $fqdn = strtolower($fqdn);
40d428d8 666 if ($fqdn == 'polytechnique.org' || $fqdn == 'melix.org' || $fqdn == 'm4x.org' || $fqdn == 'melix.net') {
81b5b746 667 $page->assign('neuneu', true);
668 } else {
669 $page->assign('email',$email);
08cce2ff 670 $sel = XDB::query(
b1797f70
VZ
671 "SELECT e1.uid, e1.panne != 0 AS panne,
672 (count(e2.uid) + IF(FIND_IN_SET('googleapps', u.mail_storage), 1, 0)) AS nb_mails,
2d997414 673 u.nom, u.prenom, u.promo, u.hruid
81b5b746 674 FROM emails as e1
eaf30d86 675 LEFT JOIN emails as e2 ON(e1.uid = e2.uid
81b5b746 676 AND FIND_IN_SET('active', e2.flags)
677 AND e1.email != e2.email)
678 INNER JOIN auth_user_md5 as u ON(e1.uid = u.user_id)
679 WHERE e1.email = {?}
680 GROUP BY e1.uid", $email);
681 if ($x = $sel->fetchOneAssoc()) {
a7de4ef7 682 // on écrit dans la base que l'adresse est cassée
81b5b746 683 if (!$x['panne']) {
74938c82 684 XDB::execute("UPDATE emails
685 SET panne=NOW(),
686 last=NOW(),
687 panne_level = 1
688 WHERE email = {?}", $email);
689 } else {
690 XDB::execute("UPDATE emails
691 SET panne_level = 1
4b9ba601 692 WHERE email = {?} AND panne_level = 0", $email);
81b5b746 693 }
694 $page->assign_by_ref('x', $x);
695 }
696 }
697 }
698 }
9e570fe0 699
700 function handler_duplicated(&$page, $action = 'list', $email = null)
701 {
702 $page->changeTpl('emails/duplicated.tpl');
703
704 $states = array('pending' => 'En attente...',
a7de4ef7 705 'safe' => 'Pas d\'inquiétude',
9e570fe0 706 'unsafe' => 'Recherches en cours',
707 'dangerous' => 'Usurpations par cette adresse');
708 $page->assign('states', $states);
709
40d428d8
VZ
710 if (Post::has('action')) {
711 S::assert_xsrf_token();
46504fb3 712 }
9e570fe0 713 switch (Post::v('action')) {
46504fb3 714 case 'create':
9e570fe0 715 if (trim(Post::v('emailN')) != '') {
716 Xdb::execute('INSERT IGNORE INTO emails_watch (email, state, detection, last, uid, description)
717 VALUES ({?}, {?}, CURDATE(), NOW(), {?}, {?})',
718 trim(Post::v('emailN')), Post::v('stateN'), S::i('uid'), Post::v('descriptionN'));
719 };
720 break;
721
46504fb3 722 case 'edit':
9e570fe0 723 Xdb::execute('UPDATE emails_watch
724 SET state = {?}, last = NOW(), uid = {?}, description = {?}
725 WHERE email = {?}', Post::v('stateN'), S::i('uid'), Post::v('descriptionN'), Post::v('emailN'));
726 break;
727
46504fb3 728 default:
9e570fe0 729 if ($action == 'delete' && !is_null($email)) {
730 Xdb::execute('DELETE FROM emails_watch WHERE email = {?}', $email);
731 }
732 }
733 if ($action != 'create' && $action != 'edit') {
734 $action = 'list';
735 }
736 $page->assign('action', $action);
737
738 if ($action == 'list') {
739 $sql = "SELECT w.email, w.detection, w.state, a.alias AS forlife
740 FROM emails_watch AS w
ca6d07f4 741 LEFT JOIN emails AS e USING(email)
742 LEFT JOIN aliases AS a ON (a.id = e.uid AND a.type = 'a_vie')
9e570fe0 743 ORDER BY w.state, w.email, a.alias";
744 $it = Xdb::iterRow($sql);
745
746 $table = array();
747 $props = array();
748 while (list($email, $date, $state, $forlife) = $it->next()) {
749 if (count($props) == 0 || $props['mail'] != $email) {
750 if (count($props) > 0) {
751 $table[] = $props;
752 }
753 $props = array('mail' => $email,
754 'detection' => $date,
755 'state' => $state,
756 'users' => array($forlife));
757 } else {
758 $props['users'][] = $forlife;
759 }
760 }
761 if (count($props) > 0) {
762 $table[] = $props;
763 }
764 $page->assign('table', $table);
765 } elseif ($action == 'edit') {
766 $sql = "SELECT w.detection, w.state, w.last, w.description,
767 a1.alias AS edit, a2.alias AS forlife
768 FROM emails_watch AS w
eaf30d86 769 LEFT JOIN aliases AS a1 ON (a1.id = w.uid AND a1.type = 'a_vie')
9615c895 770 LEFT JOIN emails AS e ON (w.email = e.email)
ca6d07f4 771 LEFT JOIN aliases AS a2 ON (a2.id = e.uid AND a2.type = 'a_vie')
9e570fe0 772 WHERE w.email = {?}
773 ORDER BY a2.alias";
774 $it = Xdb::iterRow($sql, $email);
775
776 $props = array();
777 while (list($detection, $state, $last, $description, $edit, $forlife) = $it->next()) {
778 if (count($props) == 0) {
779 $props = array('mail' => $email,
780 'detection' => $detection,
781 'state' => $state,
782 'last' => $last,
783 'description' => $description,
784 'edit' => $edit,
785 'users' => array($forlife));
786 } else {
787 $props['users'][] = $forlife;
788 }
789 }
790 $page->assign('doublon', $props);
791 }
792 }
7727ffc7 793 function handler_lost(&$page, $action = 'list', $email = null)
794 {
795 $page->changeTpl('emails/lost.tpl');
eaf30d86 796
2d997414
VZ
797 $page->assign('lost_emails', XDB::iterator("
798 SELECT u.user_id, u.hruid
0e5ec860 799 FROM auth_user_md5 AS u
2d997414
VZ
800 LEFT JOIN emails AS e ON (u.user_id = e.uid AND FIND_IN_SET('active', e.flags))
801 WHERE e.uid IS NULL AND FIND_IN_SET('googleapps', u.mail_storage) = 0 AND
802 u.deces = 0 AND u.perms IN ('user', 'admin', 'disabled')
803 ORDER BY u.promo DESC, u.nom, u.prenom"));
7727ffc7 804 }
81b5b746 805}
806
a7de4ef7 807// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
81b5b746 808?>