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