2 /***************************************************************************
3 * Copyright (C) 2003-2010 Polytechnique.org *
4 * http://opensource.polytechnique.org/ *
6 * This program is free software; you can redistribute it and/or modify *
7 * it under the terms of the GNU General Public License as published by *
8 * the Free Software Foundation; either version 2 of the License, or *
9 * (at your option) any later version. *
11 * This program is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU General Public License for more details. *
16 * You should have received a copy of the GNU General Public License *
17 * along with this program; if not, write to the Free Software *
19 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
20 ***************************************************************************/
22 class EmailModule
extends PLModule
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
),
36 'emails/rewrite/in' => $this->make_hook('rewrite_in', AUTH_PUBLIC
),
37 'emails/rewrite/out' => $this->make_hook('rewrite_out', AUTH_PUBLIC
),
39 'emails/imap/in' => $this->make_hook('imap_in', AUTH_PUBLIC
),
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'),
48 function handler_emails(&$page, $action = null
, $email = null
)
51 require_once 'emails.inc.php';
53 $page->changeTpl('emails/index.tpl');
54 $page->setTitle('Mes emails');
58 // Apply the bestalias change request.
59 if ($action == 'best' && $email) {
60 if (!S
::has_xsrf_token()) {
64 XDB
::execute("UPDATE aliases
65 SET flags = TRIM(BOTH ',' FROM REPLACE(CONCAT(',', flags, ','), ',bestalias,', ','))
66 WHERE uid = {?}", $user->id());
67 XDB
::execute("UPDATE aliases
68 SET flags = CONCAT_WS(',', IF(flags = '', NULL, flags), 'bestalias')
69 WHERE uid = {?} AND alias = {?}", $user->id(), $email);
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.
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
82 WHERE uid = {?} AND type!='homonyme'
83 ORDER BY LENGTH(alias)";
84 $page->assign('aliases', XDB
::iterator($sql, $user->id()));
86 // Check for homonyms.
87 $page->assign('homonyme', $user->homonyme
);
89 // Display active redirections.
90 $redirect = new Redirect($user);
91 $page->assign('mails', $redirect->active_emails());
93 // Display, when available, the @alias_dom email alias.
97 INNER JOIN virtual_redirect AS vr USING(vid)
98 WHERE (redirect={?} OR redirect={?})
99 AND alias LIKE '%@{$globals->mail->alias_dom}'",
100 $user->forlifeEmail(),
101 // TODO: remove this über-ugly hack. The issue is that you need
102 // to remove all @m4x.org addresses in virtual_redirect first.
103 $user->login() . '@' . $globals->mail
->domain2
);
104 $page->assign('melix', $res->fetchOneCell());
107 function handler_alias(&$page, $action = null
, $value = null
)
109 require_once 'validations.inc.php';
113 $page->changeTpl('emails/alias.tpl');
114 $page->setTitle('Alias melix.net');
117 $page->assign('demande', AliasReq
::get_request($user->id()));
119 // Remove the email alias.
120 if ($action == 'delete' && $value) {
121 S
::assert_xsrf_token();
124 "DELETE virtual, virtual_redirect
126 INNER JOIN virtual_redirect USING (vid)
127 WHERE alias = {?} AND (redirect = {?} OR redirect = {?})",
128 $value, $user->forlifeEmail(), $user->m4xForlifeEmail());
131 // Fetch existing @alias_dom aliases.
132 $alias = $user->emailAlias();
133 $visibility = $user->hasProfile() && $user->profile()->alias_pub
;
134 $page->assign('actuel', $alias);
135 $page->assign('user', $user);
136 $page->assign('mail_public', $visibility);
138 if ($action == 'ask' && Env
::has('alias') && Env
::has('raison')) {
139 S
::assert_xsrf_token();
141 //Si l'utilisateur vient de faire une damande
142 $alias = Env
::v('alias');
143 $raison = Env
::v('raison');
144 $public = (Env
::v('public', 'off') == 'on') ?
'public' : 'private';
146 $page->assign('r_alias', $alias);
147 $page->assign('r_raison', $raison);
148 if ($public == 'public') {
149 $page->assign('r_public', true
);
152 //Quelques vérifications sur l'alias (caractères spéciaux)
153 if (!preg_match("/^[a-zA-Z0-9\-.]{3,20}$/", $alias)) {
154 $page->trigError("L'adresse demandée n'est pas valide."
155 . " Vérifie qu'elle comporte entre 3 et 20 caractères"
156 . " et qu'elle ne contient que des lettres non accentuées,"
157 . " des chiffres ou les caractères - et .");
160 $alias_mail = $alias.'@'.$globals->mail
->alias_dom
;
162 //vérifier que l'alias n'est pas déja pris
163 $res = XDB
::query('SELECT COUNT(*)
167 if ($res->fetchOneCell() > 0) {
168 $page->trigError("L'alias $alias_mail a déja été attribué.
169 Tu ne peux donc pas l'obtenir.");
173 //vérifier que l'alias n'est pas déja en demande
174 $it = new ValidateIterator();
175 while($req = $it->next()) {
176 if ($req->type
== 'alias' and $req->alias
== $alias_mail) {
177 $page->trigError("L'alias $alias_mail a déja été demandé.
178 Tu ne peux donc pas l'obtenir pour l'instant.");
183 //Insertion de la demande dans la base, écrase les requêtes précédente
184 $myalias = new AliasReq($user, $alias, $raison, $public);
186 $page->assign('success',$alias);
189 } elseif ($action == 'set' && ($value == 'public' ||
$value == 'private')) {
190 if (!S
::has_xsrf_token()) {
194 if ($user->hasProfile()) {
195 XDB
::execute("UPDATE profiles
198 $value, $user->profile()->id());
200 $visibility = ($value == 'public');
203 $page->assign('actuel', $alias);
204 $page->assign('user', $user);
205 $page->assign('mail_public', $visibility);
208 function handler_redirect(&$page, $action = null
, $email = null
)
212 require_once 'emails.inc.php';
214 $page->changeTpl('emails/redirect.tpl');
217 $page->assign_by_ref('user', $user);
218 $page->assign('eleve', $user->promo() >= date("Y") - 5);
220 $redirect = new Redirect($user);
222 // FS#703 : $_GET is urldecoded twice, hence
223 // + (the data) => %2B (in the url) => + (first decoding) => ' ' (second decoding)
224 // Since there can be no spaces in emails, we can fix this with :
225 $email = str_replace(' ', '+', $email);
227 // Apply email redirection change requests.
229 if ($action == 'remove' && $email) {
230 $result = $redirect->delete_email($email);
233 if ($action == 'active' && $email) {
234 $redirect->modify_one_email($email, true
);
237 if ($action == 'inactive' && $email) {
238 $redirect->modify_one_email($email, false
);
241 if ($action == 'rewrite' && $email) {
242 $rewrite = @func_get_arg
(3);
243 $redirect->modify_one_email_redirect($email, $rewrite);
246 if (Env
::has('emailop')) {
247 S
::assert_xsrf_token();
249 $actifs = Env
::v('emails_actifs', Array());
250 print_r(Env
::v('emails_rewrite'));
251 if (Env
::v('emailop') == "ajouter" && Env
::has('email')) {
252 $new_email = Env
::v('email');
253 if ($new_email == "new@example.org") {
254 $new_email = Env
::v('email_new');
256 $result = $redirect->add_email($new_email);
257 if ($result == ERROR_INVALID_EMAIL
) {
258 $page->assign('email', $new_email);
260 $page->assign('retour', $result);
261 } elseif (empty($actifs)) {
262 $result = ERROR_INACTIVE_REDIRECTION
;
263 } elseif (is_array($actifs)) {
264 $result = $redirect->modify_email($actifs, Env
::v('emails_rewrite', Array()));
269 case ERROR_INACTIVE_REDIRECTION
:
270 $page->trigError('Tu ne peux pas avoir aucune adresse de redirection active, sinon ton adresse '
271 . $user->forlifeEmail() . ' ne fonctionnerait plus.');
273 case ERROR_INVALID_EMAIL
:
274 $page->trigError('Erreur: l\'email n\'est pas valide.');
276 case ERROR_LOOP_EMAIL
:
277 $page->trigError('Erreur : ' . $user->forlifeEmail()
278 . ' ne doit pas être renvoyé vers lui-même, ni vers son équivalent en '
279 . $globals->mail
->domain2
. ' ni vers polytechnique.edu.');
283 // Fetch the @alias_dom email alias, if any.
287 INNER JOIN virtual_redirect USING(vid)
288 WHERE (redirect={?} OR redirect={?})
289 AND alias LIKE '%@{$globals->mail->alias_dom}'",
290 $user->forlifeEmail(),
291 // TODO: remove this über-ugly hack. The issue is that you need
292 // to remove all @m4x.org addresses in virtual_redirect first.
293 $user->login() . '@' . $globals->mail
->domain2
);
294 $melix = $res->fetchOneCell();
296 list($melix) = explode('@', $melix);
297 $page->assign('melix',$melix);
300 // Fetch existing email aliases.
304 WHERE uid={?} AND (type='a_vie' OR type='alias')
305 ORDER BY !FIND_IN_SET('usage',flags), LENGTH(alias)", $user->id());
306 $page->assign('alias', $res->fetchAllAssoc());
307 $page->assign('emails', $redirect->emails
);
309 // Display GoogleApps acount information.
310 require_once 'googleapps.inc.php';
311 $page->assign('googleapps', GoogleAppsAccount
::account_status($user->id()));
313 require_once 'emails.combobox.inc.php';
314 fill_email_combobox($page);
317 function handler_antispam(&$page, $statut_filtre = null
)
319 require_once 'emails.inc.php';
320 $wp = new PlWikiPage('Xorg.Antispam');
323 $page->changeTpl('emails/antispam.tpl');
326 $bogo = new Bogo($user);
327 if (isset($statut_filtre)) {
328 $bogo->change($statut_filtre +
0);
330 $page->assign('filtre', $bogo->level());
333 function handler_submit(&$page)
335 $wp = new PlWikiPage('Xorg.Mails');
337 $page->changeTpl('emails/submit_spam.tpl');
339 if (Post
::has('send_email')) {
340 S
::assert_xsrf_token();
342 $upload = PlUpload
::get($_FILES['mail'], S
::user()->login(), 'spam.submit', true
);
344 $page->trigError('Une erreur a été rencontrée lors du transfert du fichier');
347 $mime = $upload->contentType();
348 if ($mime != 'text/x-mail' && $mime != 'message/rfc822') {
350 $page->trigError('Le fichier ne contient pas un email complet');
353 $type = (Post
::v('type') == 'spam' ?
'spam' : 'nonspam');
356 $box = $type . '@' . $globals->mail
->domain
;
357 $mailer = new PlMailer();
358 $mailer->addTo($box);
359 $mailer->setFrom('"' . S
::user()->fullName() . '" <web@' . $globals->mail
->domain
. '>');
360 $mailer->setTxtBody($type . ' soumis par ' . S
::user()->login() . ' via le web');
361 $mailer->addUploadAttachment($upload, $type . '.mail');
363 $page->trigSuccess('Le message a été transmis à ' . $box);
368 function handler_send(&$page)
370 $page->changeTpl('emails/send.tpl');
371 $page->addJsLink('ajax.js');
373 $page->setTitle('Envoyer un email');
375 // action si on recoit un formulaire
376 if (Post
::has('save')) {
377 if (!S
::has_xsrf_token()) {
381 unset($_POST['save']);
382 if (trim(preg_replace('/-- .*/', '', Post
::v('contenu'))) != "") {
383 $_POST['to_contacts'] = explode(';', @$_POST['to_contacts']);
384 $_POST['cc_contacts'] = explode(';', @$_POST['cc_contacts']);
385 $data = serialize($_POST);
386 XDB
::execute("REPLACE INTO email_send_save
388 S
::user()->id('uid'), $data);
391 } else if (Env
::v('submit') == 'Envoyer') {
392 S
::assert_xsrf_token();
394 function getEmails($aliases)
396 if (!is_array($aliases)) {
399 $uf = new UserFilter(new UFC_Hrpid($aliases));
400 $users = $uf->iterUsers();
402 while ($user = $users->next()) {
403 $ret[] = $user->forlife
;
405 return join(', ', $ret);
409 foreach ($_FILES as &$file) {
410 if ($file['name'] && !PlUpload
::get($file, S
::user()->login(), 'emails.send', false
)) {
411 $page->trigError(PlUpload
::$lastError);
418 XDB
::execute("DELETE FROM email_send_save
422 $to2 = getEmails(Env
::v('to_contacts'));
423 $cc2 = getEmails(Env
::v('cc_contacts'));
424 $txt = str_replace('^M', '', Env
::v('contenu'));
425 $to = str_replace(';', ',', Env
::t('to'));
426 $subj = Env
::t('sujet');
427 $from = Env
::t('from');
428 $cc = str_replace(';', ',', Env
::t('cc'));
429 $bcc = str_replace(';', ',', Env
::t('bcc'));
431 $email_regex = '/^[a-z0-9.\-+_\$]+@([\-.+_]?[a-z0-9])+$/i';
432 foreach (explode(',', $to . ',' . $cc . ',' . $bcc) as $email) {
433 $email = trim($email);
434 if ($email != '' && !preg_match($email_regex, $email)) {
435 $page->trigError("L'adresse email " . $email . ' est erronée.');
439 if (empty($to) && empty($cc) && empty($to2) && empty($bcc) && empty($cc2)) {
440 $page->trigError("Indique au moins un destinataire.");
445 $page->assign('uploaded_f', PlUpload
::listFilenames(S
::user()->login(), 'emails.send'));
447 $mymail = new PlMailer();
448 $mymail->setFrom($from);
449 $mymail->setSubject($subj);
450 if (!empty($to)) { $mymail->addTo($to); }
451 if (!empty($cc)) { $mymail->addCc($cc); }
452 if (!empty($bcc)) { $mymail->addBcc($bcc); }
453 if (!empty($to2)) { $mymail->addTo($to2); }
454 if (!empty($cc2)) { $mymail->addCc($cc2); }
455 $files =& PlUpload
::listFiles(S
::user()->login(), 'emails.send');
456 foreach ($files as $name=>&$upload) {
457 $mymail->addUploadAttachment($upload, $name);
459 if (Env
::v('nowiki')) {
460 $mymail->setTxtBody(wordwrap($txt, 78, "\n"));
462 $mymail->setWikiBody($txt);
464 if ($mymail->send()) {
465 $page->trigSuccess("Ton email a bien été envoyé.");
466 $_REQUEST = array('bcc' => S
::user()->bestEmail());
467 PlUpload
::clear(S
::user()->login(), 'emails.send');
469 $page->trigError("Erreur lors de l'envoi du courriel, réessaye.");
470 $page->assign('uploaded_f', PlUpload
::listFilenames(S
::user()->login(), 'emails.send'));
475 $res = XDB
::query("SELECT data
477 WHERE uid = {?}", S
::i('uid'));
478 if ($res->numRows() == 0) {
479 PlUpload
::clear(S
::user()->login(), 'emails.send');
480 $_REQUEST['bcc'] = S
::user()->bestEmail();
482 $data = unserialize($res->fetchOneCell());
483 $_REQUEST = array_merge($_REQUEST, $data);
487 $uf = new UserFilter(new PFC_And(new UFC_Contact(S
::user()),
488 new UFC_Registered()),
489 UserFilter
::sortByName());
490 $contacts = $uf->getProfiles();
491 $page->assign('contacts', $contacts);
492 $page->assign('maxsize', ini_get('upload_max_filesize') . 'o');
493 $page->assign('user', S
::user());
496 function handler_test(&$page, $hruid = null
)
498 require_once 'emails.inc.php';
500 if (!S
::has_xsrf_token()) {
504 // Retrieves the User object for the test email recipient.
505 if (S
::admin() && $hruid) {
506 $user = User
::getSilent($hruid);
514 // Sends the test email.
515 $redirect = new Redirect($user);
517 $mailer = new PlMailer('emails/test.mail.tpl');
518 $mailer->assign('email', $user->bestEmail());
519 $mailer->assign('redirects', $redirect->active_emails());
520 $mailer->assign('display_name', $user->displayName());
521 $mailer->assign('sexe', $user->isFemale());
522 $mailer->send($user->isEmailFormatHtml());
526 function handler_rewrite_in(&$page, $mail, $hash)
528 $page->changeTpl('emails/rewrite.tpl');
529 $page->assign('option', 'in');
530 if (empty($mail) ||
empty($hash)) {
533 $pos = strrpos($mail, '_');
534 if ($pos === false
) {
538 $res = XDB
::query("SELECT COUNT(*)
540 WHERE email = {?} AND hash = {?}",
542 $count = intval($res->fetchOneCell());
544 XDB
::query("UPDATE emails
545 SET allow_rewrite = true, hash = NULL
546 WHERE email = {?} AND hash = {?}",
548 $page->trigSuccess("Réécriture activée pour l'adresse " . $mail);
554 function handler_rewrite_out(&$page, $mail, $hash)
556 $page->changeTpl('emails/rewrite.tpl');
557 $page->assign('option', 'out');
558 if (empty($mail) ||
empty($hash)) {
561 $pos = strrpos($mail, '_');
562 if ($pos === false
) {
566 $res = XDB
::query("SELECT COUNT(*)
568 WHERE email = {?} AND hash = {?}",
570 $count = intval($res->fetchOneCell());
573 $res = XDB
::query("SELECT e.email, e.rewrite, a.alias
575 INNER JOIN aliases AS a ON (a.uid = e.uid AND a.type = 'a_vie')
576 WHERE e.email = {?} AND e.hash = {?}",
578 XDB
::query("UPDATE emails
579 SET allow_rewrite = false, hash = NULL
580 WHERE email = {?} AND hash = {?}",
582 list($mail, $rewrite, $forlife) = $res->fetchOneRow();
583 $mail = new PlMailer();
584 $mail->setFrom("webmaster@" . $globals->mail
->domain
);
585 $mail->addTo("support@" . $globals->mail
->domain
);
586 $mail->setSubject("Tentative de détournement de correspondance via le rewrite");
587 $mail->setTxtBody("$forlife a tenté un rewrite de $mail vers $rewrite. Cette demande a été rejetée via le web");
589 $page->trigWarning("Un mail d'alerte a été envoyé à l'équipe de " . $globals->core
->sitename
);
595 function handler_imap_in(&$page, $hash = null
, $login = null
)
597 $page->changeTpl('emails/imap_register.tpl');
599 if (!empty($hash) ||
!empty($login)) {
600 $user = User
::getSilent($login);
602 $req = XDB
::query('SELECT 1
604 WHERE uid = {?} AND hash = {?}',
606 if ($req->numRows() == 0) {
612 require_once('emails.inc.php');
613 $page->assign('ok', false
);
614 if (S
::logged() && (is_null($user) ||
$user->id() == S
::i('uid'))) {
615 $storage = new EmailStorage(S
::user(), 'imap');
616 $storage->activate();
617 $page->assign('ok', true
);
618 $page->assign('prenom', S
::v('prenom'));
619 $page->assign('sexe', S
::v('femme'));
620 } else if (!S
::logged() && $user) {
621 $storage = new EmailStorage($user, 'imap');
622 $storage->activate();
623 $page->assign('ok', true
);
624 $page->assign('prenom', $user->displayName());
625 $page->assign('sexe', $user->isFemale());
629 function handler_broken(&$page, $warn = null
, $email = null
)
631 require_once 'emails.inc.php';
632 $wp = new PlWikiPage('Xorg.PatteCassée');
637 $page->changeTpl('emails/broken.tpl');
639 if ($warn == 'warn' && $email) {
640 S
::assert_xsrf_token();
642 $email = valide_email($email);
643 // vérifications d'usage
644 $uid = XDB
::fetchOneCell("SELECT uid
646 WHERE email = {?}", $email);
648 $dest = User
::getWithUID($uid);
650 $mail = new PlMailer('emails/broken-web.mail.tpl');
651 $mail->assign('email', $email);
652 $mail->assign('request', S
::user());
653 $mail->sendTo($dest);
654 $page->trigSuccess('Email envoyé !');
656 } elseif (Post
::has('email')) {
657 S
::assert_xsrf_token();
659 $email = valide_email(Post
::v('email'));
661 list(,$fqdn) = explode('@', $email);
662 $fqdn = strtolower($fqdn);
663 if ($fqdn == 'polytechnique.org' ||
$fqdn == 'melix.org' ||
$fqdn == 'm4x.org' ||
$fqdn == 'melix.net') {
664 $page->assign('neuneu', true
);
666 $page->assign('email',$email);
667 $x = XDB
::fetchOneAssoc("SELECT e1.uid, e1.panne != 0 AS panne,
668 (count(e2.uid) + IF(FIND_IN_SET('googleapps', eo.storage), 1, 0)) AS nb_mails
670 INNER JOIN email_options AS eo ON (eo.uid = e1.uid)
671 LEFT JOIN emails as e2 ON(e1.uid = e2.uid
672 AND FIND_IN_SET('active', e2.flags)
673 AND e1.email != e2.email)
675 GROUP BY e1.uid", $email);
677 // on écrit dans la base que l'adresse est cassée
679 XDB
::execute("UPDATE emails
680 SET panne=NOW(), last=NOW(), panne_level = 1
681 WHERE email = {?}", $email);
683 XDB
::execute("UPDATE emails
685 WHERE email = {?} AND panne_level = 0", $email);
687 $x['user'] = User
::getWithUID($x['uid']);
688 $page->assign_by_ref('x', $x);
694 function handler_duplicated(&$page, $action = 'list', $email = null
)
696 $page->changeTpl('emails/duplicated.tpl');
698 $states = array('pending' => 'En attente...',
699 'safe' => 'Pas d\'inquiétude',
700 'unsafe' => 'Recherches en cours',
701 'dangerous' => 'Usurpations par cette adresse');
702 $page->assign('states', $states);
704 if (Post
::has('action')) {
705 S
::assert_xsrf_token();
707 switch (Post
::v('action')) {
709 if (trim(Post
::v('emailN')) != '') {
710 Xdb
::execute('INSERT IGNORE INTO email_watch (email, state, detection, last, uid, description)
711 VALUES ({?}, {?}, CURDATE(), NOW(), {?}, {?})',
712 trim(Post
::v('emailN')), Post
::v('stateN'), S
::i('uid'), Post
::v('descriptionN'));
717 Xdb
::execute('UPDATE email_watch
718 SET state = {?}, last = NOW(), uid = {?}, description = {?}
719 WHERE email = {?}', Post
::v('stateN'), S
::i('uid'), Post
::v('descriptionN'), Post
::v('emailN'));
723 if ($action == 'delete' && !is_null($email)) {
724 Xdb
::execute('DELETE FROM email_watch WHERE email = {?}', $email);
727 if ($action != 'create' && $action != 'edit') {
730 $page->assign('action', $action);
732 if ($action == 'list') {
733 $sql = "SELECT w.email, w.detection, w.state, a.alias AS forlife
734 FROM email_watch AS w
735 LEFT JOIN emails AS e USING(email)
736 LEFT JOIN aliases AS a ON (a.uid = e.uid AND a.type = 'a_vie')
737 ORDER BY w.state, w.email, a.alias";
738 $it = Xdb
::iterRow($sql);
742 while (list($email, $date, $state, $forlife) = $it->next()) {
743 if (count($props) == 0 ||
$props['mail'] != $email) {
744 if (count($props) > 0) {
747 $props = array('mail' => $email,
748 'detection' => $date,
750 'users' => array($forlife));
752 $props['users'][] = $forlife;
755 if (count($props) > 0) {
758 $page->assign('table', $table);
759 } elseif ($action == 'edit') {
760 $sql = "SELECT w.detection, w.state, w.last, w.description,
761 a1.alias AS edit, a2.alias AS forlife
762 FROM email_watch AS w
763 LEFT JOIN aliases AS a1 ON (a1.uid = w.uid AND a1.type = 'a_vie')
764 LEFT JOIN emails AS e ON (w.email = e.email)
765 LEFT JOIN aliases AS a2 ON (a2.uid = e.uid AND a2.type = 'a_vie')
768 $it = Xdb
::iterRow($sql, $email);
771 while (list($detection, $state, $last, $description, $edit, $forlife) = $it->next()) {
772 if (count($props) == 0) {
773 $props = array('mail' => $email,
774 'detection' => $detection,
777 'description' => $description,
779 'users' => array($forlife));
781 $props['users'][] = $forlife;
784 $page->assign('doublon', $props);
788 function handler_lost(&$page, $action = 'list', $email = null
)
790 $page->changeTpl('emails/lost.tpl');
792 // TODO: Order by promo.
793 $page->assign('lost_emails',
794 XDB
::iterator("SELECT a.uid, a.hruid
796 INNER JOIN email_options AS eo ON (eo.uid = a.uid)
797 LEFT JOIN emails AS e ON (a.uid = e.uid AND FIND_IN_SET('active', e.flags))
798 WHERE e.uid IS NULL AND FIND_IN_SET('googleapps', eo.storage) = 0 AND
803 function handler_broken_addr(&$page)
805 require_once 'emails.inc.php';
806 $page->changeTpl('emails/broken_addr.tpl');
808 if (Env
::has('sort_broken')) {
809 S
::assert_xsrf_token();
811 $list = trim(Env
::v('list'));
813 $page->trigError('La liste est vide.');
815 $valid_emails = array();
816 $invalid_emails = array();
817 $broken_list = explode("\n", $list);
819 foreach ($broken_list as $orig_email) {
820 $orig_email = trim($orig_email);
821 if ($orig_email != '') {
822 $email = valide_email($orig_email);
823 if (empty($email) ||
$email == '@') {
824 $invalid_emails[] = trim($orig_email) . ': invalid email';
825 } elseif (!in_array($email, $valid_emails)) {
826 $res = XDB
::query('SELECT COUNT(*)
828 WHERE email = {?}', $email);
829 if ($res->fetchOneCell() > 0) {
830 $valid_emails[] = $email;
832 $invalid_emails[] = "$orig_email: no such redirection";
838 $page->assign('valid_emails', $valid_emails);
839 $page->assign('invalid_emails', $invalid_emails);
843 if (Env
::has('process_broken')) {
844 S
::assert_xsrf_token();
846 $list = trim(Env
::v('list'));
848 $page->trigError('La liste est vide.');
852 $broken_user_list = array();
853 $broken_list = explode("\n", $list);
855 foreach ($broken_list as $orig_email) {
856 $email = valide_email(trim($orig_email));
857 if (empty($email) ||
$email == '@') {
862 "SELECT e1.uid, e1.panne != 0 AS panne, count(e2.uid) AS nb_mails,
863 acc.full_name, a.alias
865 LEFT JOIN emails AS e2 ON (e1.uid = e2.uid AND FIND_IN_SET('active', e2.flags)
866 AND e1.email != e2.email)
867 INNER JOIN accounts AS acc ON (e1.uid = acc.uid)
868 INNER JOIN aliases AS a ON (acc.uid = a.uid AND FIND_IN_SET('bestalias', a.flags))
870 GROUP BY e1.uid", $email);
872 if ($x = $sel->fetchOneAssoc()) {
874 XDB
::execute('UPDATE emails
875 SET panne=NOW(), last=NOW(), panne_level = 1
879 XDB
::execute('UPDATE emails
880 SET last = CURDATE(), panne_level = panne_level + 1
882 AND DATE_ADD(last, INTERVAL 14 DAY) < CURDATE()',
886 if (!empty($x['nb_mails'])) {
887 $mail = new PlMailer('emails/broken.mail.tpl');
888 $mail->addTo("\"{$x['full_name']}\" <{$x['alias']}@"
889 . $globals->mail
->domain
. '>');
890 $mail->assign('x', $x);
891 $mail->assign('email', $email);
895 if (!isset($broken_user_list[$x['alias']])) {
896 $broken_user_list[$x['alias']] = array($email);
898 $broken_user_list[$x['alias']][] = $email;
903 XDB
::execute("UPDATE emails
904 SET panne_level = panne_level - 1
905 WHERE flags = 'active' AND panne_level > 1
906 AND DATE_ADD(last, INTERVAL 1 MONTH) < CURDATE()");
907 XDB
::execute("UPDATE emails
909 WHERE flags = 'active' AND panne_level = 1
910 AND DATE_ADD(last, INTERVAL 1 YEAR) < CURDATE()");
912 // Output the list of users with recently broken addresses,
913 // along with the count of valid redirections.
914 require_once 'notifs.inc.php';
915 pl_content_headers("text/x-csv");
917 $csv = fopen('php://output', 'w');
918 fputcsv($csv, array('nom', 'promo', 'alias', 'bounce', 'nbmails', 'url'), ';');
919 foreach ($broken_user_list as $alias => $mails) {
921 "SELECT acc.uid, count(e.email) AS nb_mails,
922 IFNULL(pd.public_name, acc.full_name) AS fullname,
923 IFNULL(pd.promo, 0) AS promo
925 INNER JOIN accounts AS acc ON (a.uid = acc.uid)
926 LEFT JOIN emails AS e ON (e.uid = acc.uid
927 AND FIND_IN_SET('active', e.flags) AND e.panne = 0)
928 LEFT JOIN account_profiles AS ap ON (acc.uid = ap.uid AND FIND_IN_SET('owner', ap.perms))
929 LEFT JOIN profile_display AS pd ON (pd.pid = ap.pid)
931 GROUP BY acc.uid", $alias);
933 if ($x = $sel->fetchOneAssoc()) {
934 if ($x['nb_mails'] == 0) {
935 $user = User
::getSilentWithUID($x['uid']);
936 $profile = $user->profile();
937 WatchProfileUpdate
::register($profile, 'broken');
939 fputcsv($csv, array($x['fullname'], $x['promo'], $alias,
940 join(',', $mails), $x['nb_mails'],
941 'https://www.polytechnique.org/marketing/broken/' . $alias), ';');
951 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: