2 /***************************************************************************
3 * Copyright (C) 2003-2014 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
, 'mail'),
28 'emails/alias' => $this->make_hook('alias', AUTH_PASSWD
, 'mail'),
29 'emails/antispam' => $this->make_hook('antispam', AUTH_PASSWD
, 'mail'),
30 'emails/broken' => $this->make_hook('broken', AUTH_COOKIE
, 'user'),
31 'emails/redirect' => $this->make_hook('redirect', AUTH_PASSWD
, 'mail'),
32 'emails/send' => $this->make_hook('send', AUTH_PASSWD
, 'mail'),
33 'emails/antispam/submit' => $this->make_hook('submit', AUTH_COOKIE
, 'user'),
34 'emails/test' => $this->make_hook('test', AUTH_COOKIE
, 'mail', 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_PASSWD
, 'admin'),
42 'admin/emails/watch' => $this->make_hook('duplicated', AUTH_PASSWD
, 'admin'),
43 'admin/emails/lost' => $this->make_hook('lost', AUTH_PASSWD
, 'admin'),
44 'admin/emails/broken' => $this->make_hook('broken_addr', AUTH_PASSWD
, 'admin,edit_directory'),
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 // First delete the bestalias flag from all this user's emails.
65 XDB
::execute("UPDATE email_source_account
66 SET flags = TRIM(BOTH ',' FROM REPLACE(CONCAT(',', flags, ','), ',bestalias,', ','))
67 WHERE uid = {?}", $user->id());
68 // Then gives the bestalias flag to the given email.
69 list($email, $domain) = explode('@', $email);
70 XDB
::execute("UPDATE email_source_account AS s
71 INNER JOIN email_virtual_domains AS m ON (m.id = s.domain)
72 INNER JOIN email_virtual_domains AS d ON (d.aliasing = m.id)
73 SET flags = CONCAT_WS(',', IF(flags = '', NULL, flags), 'bestalias')
74 WHERE s.uid = {?} AND s.email = {?} AND d.name = {?}",
75 $user->id(), $email, $domain);
76 XDB
::execute('UPDATE accounts AS a
77 INNER JOIN email_virtual_domains AS d ON (d.name = {?})
78 INNER JOIN email_virtual_domains AS m ON (d.aliasing = m.id)
79 SET a.best_domain = d.id
80 WHERE a.uid = {?} AND m.name = {?}',
81 $domain, $user->id(), $user->mainEmailDomain());
83 // As having a non-null bestalias value is critical in
84 // plat/al's code, we do an a posteriori check on the
85 // validity of the bestalias.
87 // Then refetch the user to update its bestalias.
88 S
::set('user', User
::getWithUID(S
::user()->id()));
91 // Fetch and display aliases.
92 $aliases = XDB
::iterator("SELECT CONCAT(s.email, '@', d.name) AS email, (s.type = 'forlife') AS forlife,
93 (s.email REGEXP '\\\\.[0-9]{2}$') AS hundred_year, s.expire,
94 (FIND_IN_SET('bestalias', s.flags) AND a.best_domain = d.id) AS bestalias,
95 ((s.type = 'alias_aux') AND d.aliasing = d.id) AS alias
96 FROM email_source_account AS s
97 INNER JOIN accounts AS a ON (s.uid = a.uid)
98 INNER JOIN email_virtual_domains AS m ON (s.domain = m.id)
99 INNER JOIN email_virtual_domains AS d ON (d.aliasing = m.id)
101 ORDER BY !alias, s.email, d.name",
103 $aliases_forlife = array();
104 $aliases_hundred = array();
105 $aliases_other = array();
106 while ($a = $aliases->next()) {
108 $aliases_forlife[] = $a;
109 } elseif ($a['hundred_year']) {
110 $aliases_hundred[] = $a;
112 $aliases_other[] = $a;
115 $page->assign('aliases_forlife', $aliases_forlife);
116 $page->assign('aliases_hundred', $aliases_hundred);
117 $page->assign('aliases_other', $aliases_other);
119 $alias = XDB
::fetchOneCell('SELECT COUNT(email)
120 FROM email_source_account
121 WHERE uid = {?} AND type = \'alias_aux\'',
123 $page->assign('alias', $alias);
126 // Check for homonyms.
127 $page->assign('homonyme', $user->homonyme
);
129 // Display active redirections.
130 $redirect = new Redirect($user);
131 $page->assign('mails', $redirect->active_emails());
133 // User's mail domains.
134 $mail_domains = array($user->alternateEmailDomain());
135 $mail_domains[] = User
::$sub_mail_domains['all'] . $globals->mail
->domain
;
136 $mail_domains[] = User
::$sub_mail_domains['all'] . $globals->mail
->domain2
;
137 $page->assign('main_email_domain', $user->mainEmailDomain());
138 $page->assign('mail_domains', $mail_domains);
141 function handler_alias($page, $action = null
, $value = null
)
145 $page->changeTpl('emails/alias.tpl');
146 $page->setTitle('Alias melix.net');
149 $page->assign('request', AliasReq
::get_request($user->id()));
151 // Remove the email alias.
152 if ($action == 'delete') {
153 S
::assert_xsrf_token();
155 XDB
::execute('DELETE FROM email_source_account
156 WHERE uid = {?} AND type = \'alias_aux\'',
159 require_once 'emails.inc.php';
160 fix_bestalias($user);
163 // Fetch existing auxiliary aliases.
164 list($alias, $old_alias) = XDB
::fetchOneRow('SELECT CONCAT(s.email, \'@\', d.name), s.email
165 FROM email_source_account AS s
166 INNER JOIN email_virtual_domains AS d ON (s.domain = d.id)
167 WHERE s.uid = {?} AND s.type = \'alias_aux\'',
169 $visibility = $user->hasProfile() && $user->profile()->isVisible($user->profile()->alias_pub
);
170 $page->assign('current', $alias);
171 $page->assign('user', $user);
172 $page->assign('mail_public', $visibility);
174 if ($action == 'ask' && Env
::has('alias') && Env
::has('reason')) {
175 S
::assert_xsrf_token();
177 // Retrieves user request.
178 $new_alias = Env
::v('alias');
179 $reason = Env
::v('reason');
180 $public = (Env
::v('public', 'off') == 'on') ?
'private' : 'hidden';
182 $page->assign('r_alias', $new_alias);
183 $page->assign('r_reason', $reason);
184 if ($public == 'private') {
185 $page->assign('r_public', true
);
188 // Checks special charaters in alias.
189 if (!preg_match("/^[a-zA-Z0-9\-.]{2,19}[a-zA-Z0-9\-]$/", $new_alias)) {
190 $page->trigError("L'adresse demandée n'est pas valide."
191 . " Vérifie qu'elle comporte entre 3 et 20 caractères"
192 . " et qu'elle ne contient que des lettres non accentuées,"
193 . " des chiffres ou les caractères '-' et '.'. De plus, elle ne"
194 . " peut pas se terminer par un point.");
197 // Checks if the alias has already been given.
198 $res = XDB
::query('SELECT COUNT(email)
199 FROM email_source_account
200 WHERE email = {?} AND type = \'alias_aux\'',
202 if ($res->fetchOneCell() > 0) {
203 $page->trigError("L'alias $new_alias a déja été attribué. Tu ne peux donc pas l'obtenir.");
207 // Checks if the alias has already been asked for.
208 $it = Validate
::iterate('alias');
209 while($req = $it->next()) {
210 if ($req->alias
== $new_alias) {
211 $page->trigError("L'alias $new_alias a déja été demandé. Tu ne peux donc pas l'obtenir pour l'instant.");
216 // Sends requests. This will erase any previous alias pending request.
217 $myalias = new AliasReq($user, $new_alias, $reason, $public, $old_alias);
219 $page->assign('success', $new_alias);
222 } elseif ($action == 'set' && ($value == 'public' ||
$value == 'private')) {
223 if (!S
::has_xsrf_token()) {
227 if ($user->hasProfile()) {
228 XDB
::execute('UPDATE profiles
231 $value, $user->profile()->id());
237 function handler_redirect($page, $action = null
, $email = null
, $rewrite = null
)
240 require_once 'emails.inc.php';
242 $page->changeTpl('emails/redirect.tpl');
245 $page->assign_by_ref('user', $user);
246 $page->assign('eleve', $user->promo() >= date("Y") - 5);
248 $redirect = new Redirect($user);
250 // FS#703 : $_GET is urldecoded twice, hence
251 // + (the data) => %2B (in the url) => + (first decoding) => ' ' (second decoding)
252 // Since there can be no spaces in emails, we can fix this with :
253 $email = str_replace(' ', '+', $email);
255 // Apply email redirection change requests.
257 if ($action == 'remove' && $email) {
258 $result = $redirect->delete_email($email);
261 if ($action == 'active' && $email) {
262 $redirect->modify_one_email($email, true
);
265 if ($action == 'inactive' && $email) {
266 $redirect->modify_one_email($email, false
);
269 if ($action == 'rewrite' && $email) {
270 $redirect->modify_one_email_redirect($email, $rewrite);
273 if (Env
::has('emailop')) {
274 S
::assert_xsrf_token();
276 $actifs = Env
::v('emails_actifs', array());
277 if (Env
::v('emailop') == "ajouter" && Env
::has('email')) {
278 $error_email = false
;
279 $new_email = Env
::v('email');
280 if ($new_email == "new@example.org") {
281 $new_email = Env
::v('email_new');
283 $result = $redirect->add_email($new_email);
284 if ($result == ERROR_INVALID_EMAIL
) {
286 $page->assign('email', $new_email);
288 $page->assign('retour', $result);
289 $page->assign('error_email', $error_email);
290 } elseif (empty($actifs)) {
291 $result = ERROR_INACTIVE_REDIRECTION
;
292 } elseif (is_array($actifs)) {
293 $result = $redirect->modify_email($actifs, Env
::v('emails_rewrite', array()));
298 case ERROR_INACTIVE_REDIRECTION
:
299 $page->trigError('Tu ne peux pas avoir aucune adresse de redirection active, sinon ton adresse '
300 . $user->forlifeEmail() . ' ne fonctionnerait plus.');
302 case ERROR_INVALID_EMAIL
:
303 $page->trigError('Erreur : l\'email n\'est pas valide.');
305 case ERROR_LOOP_EMAIL
:
306 $page->trigError('Erreur : ' . $user->forlifeEmail()
307 . ' ne doit pas être renvoyé vers lui-même, ni vers son équivalent en '
308 . $globals->mail
->domain2
. ' ni vers polytechnique.edu.');
311 // Fetch existing email aliases.
312 $alias = XDB
::query('SELECT CONCAT(s.email, \'@\', d.name) AS email, s.expire
313 FROM email_source_account AS s
314 INNER JOIN email_virtual_domains AS m ON (s.domain = m.id)
315 INNER JOIN email_virtual_domains AS d ON (m.id = d.aliasing)
317 ORDER BY NOT(s.type = \'alias_aux\'), s.email, d.name',
319 $page->assign('alias', $alias->fetchAllAssoc());
320 $page->assign('best_email', $user->bestEmail());
322 $page->assign('emails', $redirect->emails
);
324 // Display GoogleApps acount information.
325 require_once 'googleapps.inc.php';
326 $page->assign('googleapps', GoogleAppsAccount
::account_status($user->id()));
328 require_once 'emails.combobox.inc.php';
329 fill_email_combobox($page, array('job', 'stripped_directory'));
332 function handler_antispam($page, $filter_status = null
, $redirection = null
)
334 require_once 'emails.inc.php';
335 $wp = new PlWikiPage('Xorg.Antispam');
338 $page->changeTpl('emails/antispam.tpl');
341 $bogo = new Bogo($user);
342 if (!is_null($filter_status)) {
343 if (is_null($redirection)) {
344 $bogo->changeAll($filter_status);
346 $bogo->change($redirection, $filter_status);
349 $page->assign('filter', $bogo->state
);
350 $page->assign('single_state', $bogo->single_state
);
351 $page->assign('single_redirection', $bogo->single_redirection
);
352 $page->assign('redirections', $bogo->redirections
);
355 function handler_submit($page)
357 $wp = new PlWikiPage('Xorg.Mails');
359 $page->changeTpl('emails/submit_spam.tpl');
361 if (Post
::has('send_email')) {
362 S
::assert_xsrf_token();
364 $upload = PlUpload
::get($_FILES['mail'], S
::user()->login(), 'spam.submit', true
);
366 $page->trigError('Une erreur a été rencontrée lors du transfert du fichier');
369 $mime = $upload->contentType();
370 if ($mime != 'text/x-mail' && $mime != 'message/rfc822') {
372 $page->trigError('Le fichier ne contient pas un email complet');
375 $type = (Post
::v('type') == 'spam' ?
'spam' : 'nonspam');
378 $box = $type . '@' . $globals->mail
->domain
;
379 $mailer = new PlMailer();
380 $mailer->addTo($box);
381 $mailer->setFrom('"' . S
::user()->fullName() . '" <web@' . $globals->mail
->domain
. '>');
382 $mailer->setTxtBody($type . ' soumis par ' . S
::user()->login() . ' via le web');
383 $mailer->addUploadAttachment($upload, $type . '.mail');
385 $page->trigSuccess('Le message a été transmis à ' . $box);
390 function handler_send($page)
392 $page->changeTpl('emails/send.tpl');
394 $page->setTitle('Envoyer un email');
396 // action si on recoit un formulaire
397 if (Post
::has('save')) {
398 if (!S
::has_xsrf_token()) {
402 unset($_POST['save']);
403 if (trim(preg_replace('/-- .*/', '', Post
::v('contenu'))) != "") {
404 Post
::set('to_contacts', explode(';', Post
::s('to_contacts')));
405 Post
::set('cc_contacts', explode(';', Post
::s('cc_contacts')));
406 $data = serialize($_POST);
407 XDB
::execute('INSERT INTO email_send_save (uid, data)
409 ON DUPLICATE KEY UPDATE data = VALUES(data)',
410 S
::user()->id('uid'), $data);
413 } else if (Env
::v('submit') == 'Envoyer') {
414 S
::assert_xsrf_token();
416 function getEmails($aliases)
418 if (!is_array($aliases)) {
421 $uf = new UserFilter(new UFC_Hrpid($aliases));
422 $users = $uf->iterUsers();
424 while ($user = $users->next()) {
425 $ret[] = $user->forlife
;
427 return join(', ', $ret);
431 foreach ($_FILES as &$file) {
432 if ($file['name'] && !PlUpload
::get($file, S
::user()->login(), 'emails.send', false
)) {
433 $page->trigError(PlUpload
::$lastError);
440 XDB
::execute("DELETE FROM email_send_save
444 $to2 = getEmails(Env
::v('to_contacts'));
445 $cc2 = getEmails(Env
::v('cc_contacts'));
446 $txt = str_replace('^M', '', Env
::v('contenu'));
447 $to = str_replace(';', ',', Env
::t('to'));
448 $subj = Env
::t('sujet');
449 $from = Env
::t('from');
450 $cc = str_replace(';', ',', Env
::t('cc'));
451 $bcc = str_replace(';', ',', Env
::t('bcc'));
453 $email_regex = '/^[a-z0-9.\-+_\$]+@([\-.+_]?[a-z0-9])+$/i';
454 foreach (explode(',', $to . ',' . $cc . ',' . $bcc) as $email) {
455 $email = trim($email);
456 if ($email != '' && !preg_match($email_regex, $email)) {
457 $page->trigError("L'adresse email " . $email . ' est erronée.');
461 if (empty($to) && empty($cc) && empty($to2) && empty($bcc) && empty($cc2)) {
462 $page->trigError("Indique au moins un destinataire.");
467 $page->assign('uploaded_f', PlUpload
::listFilenames(S
::user()->login(), 'emails.send'));
469 $mymail = new PlMailer();
470 $mymail->setFrom($from);
471 $mymail->setSubject($subj);
472 if (!empty($to)) { $mymail->addTo($to); }
473 if (!empty($cc)) { $mymail->addCc($cc); }
474 if (!empty($bcc)) { $mymail->addBcc($bcc); }
475 if (!empty($to2)) { $mymail->addTo($to2); }
476 if (!empty($cc2)) { $mymail->addCc($cc2); }
477 $files =& PlUpload
::listFiles(S
::user()->login(), 'emails.send');
478 foreach ($files as $name=>&$upload) {
479 $mymail->addUploadAttachment($upload, $name);
481 if (Env
::v('wiki') == 'text') {
482 $mymail->setTxtBody(wordwrap($txt, 78, "\n"));
484 $mymail->setWikiBody($txt);
486 if ($mymail->send()) {
487 $page->trigSuccess("Ton email a bien été envoyé.");
488 $_REQUEST = array('bcc' => S
::user()->bestEmail());
489 PlUpload
::clear(S
::user()->login(), 'emails.send');
491 $page->trigError("Erreur lors de l'envoi du courriel, réessaye.");
492 $page->assign('uploaded_f', PlUpload
::listFilenames(S
::user()->login(), 'emails.send'));
497 $res = XDB
::query("SELECT data
499 WHERE uid = {?}", S
::i('uid'));
500 if ($res->numRows() == 0) {
501 PlUpload
::clear(S
::user()->login(), 'emails.send');
502 $_REQUEST['bcc'] = S
::user()->bestEmail();
504 $data = unserialize($res->fetchOneCell());
505 $_REQUEST = array_merge($_REQUEST, $data);
509 $uf = new UserFilter(new PFC_And(new UFC_Contact(S
::user()),
510 new UFC_Registered()),
511 UserFilter
::sortByName());
512 $contacts = $uf->getProfiles();
513 $page->assign('contacts', $contacts);
514 $page->assign('maxsize', ini_get('upload_max_filesize') . 'o');
515 $page->assign('user', S
::user());
516 $preferences = XDB
::fetchOneAssoc('SELECT from_email, from_format
520 if ($preferences['from_email'] == '') {
521 $preferences['from_email'] = '"' . S
::user()->fullName() . '" <' . S
::user()->bestEmail() . '>';
523 $page->assign('preferences', $preferences);
526 function handler_test($page, $hruid = null
)
528 require_once 'emails.inc.php';
530 if (!S
::has_xsrf_token()) {
534 // Retrieves the User object for the test email recipient.
535 if (S
::admin() && $hruid) {
536 $user = User
::getSilent($hruid);
544 // Sends the test email.
545 $redirect = new Redirect($user);
547 $mailer = new PlMailer('emails/test.mail.tpl');
548 $mailer->assign('email', $user->bestEmail());
549 $mailer->assign('redirects', $redirect->active_emails());
550 $mailer->assign('display_name', $user->displayName());
551 $mailer->assign('sexe', $user->isFemale());
552 $mailer->send($user->isEmailFormatHtml());
556 function handler_rewrite_in($page, $mail, $hash)
558 $page->changeTpl('emails/rewrite.tpl');
559 $page->assign('option', 'in');
560 if (empty($mail) ||
empty($hash)) {
563 $pos = strrpos($mail, '_');
564 if ($pos === false
) {
568 $res = XDB
::query('SELECT COUNT(*)
569 FROM email_redirect_account
570 WHERE redirect = {?} AND hash = {?} AND type = \'smtp\'',
572 $count = intval($res->fetchOneCell());
574 XDB
::query('UPDATE email_redirect_account
575 SET allow_rewrite = true, hash = NULL
576 WHERE redirect = {?} AND hash = {?} AND type = \'smtp\'',
578 $page->trigSuccess("Réécriture activée pour l'adresse " . $mail);
584 function handler_rewrite_out($page, $mail, $hash)
586 $page->changeTpl('emails/rewrite.tpl');
587 $page->assign('option', 'out');
588 if (empty($mail) ||
empty($hash)) {
591 $pos = strrpos($mail, '_');
592 if ($pos === false
) {
596 $res = XDB
::query('SELECT COUNT(*)
597 FROM email_redirect_account
598 WHERE redirect = {?} AND hash = {?} AND type = \'smtp\'',
600 $count = intval($res->fetchOneCell());
603 $res = XDB
::query('SELECT e.redirect, e.rewrite, a.hruid
604 FROM email_redirect_account AS e
605 INNER JOIN accounts AS a ON (e.uid = a.uid)
606 WHERE e.redirect = {?} AND e.hash = {?}',
608 XDB
::query('UPDATE email_redirect_account
609 SET allow_rewrite = false, hash = NULL
610 WHERE redirect = {?} AND hash = {?}',
612 list($mail, $rewrite, $hruid) = $res->fetchOneRow();
613 $mail = new PlMailer();
614 $mail->setFrom("webmaster@" . $globals->mail
->domain
);
615 $mail->addTo("support@" . $globals->mail
->domain
);
616 $mail->setSubject("Tentative de détournement de correspondance via le rewrite");
617 $mail->setTxtBody("$hruid a tenté un rewrite de $mail vers $rewrite. Cette demande a été rejetée via le web");
619 $page->trigWarning("Un mail d'alerte a été envoyé à l'équipe de " . $globals->core
->sitename
);
625 function handler_imap_in($page, $hash = null
, $login = null
)
627 $page->changeTpl('emails/imap_register.tpl');
629 if (!empty($hash) ||
!empty($login)) {
630 $user = User
::getSilent($login);
632 $req = XDB
::query('SELECT 1
634 WHERE uid = {?} AND hash = {?}',
636 if ($req->numRows() == 0) {
642 require_once 'emails.inc.php';
643 $page->assign('ok', false
);
644 if (S
::logged() && (is_null($user) ||
$user->id() == S
::i('uid'))) {
645 Email
::activate_storage(S
::user(), 'imap', Bogo
::IMAP_DEFAULT
);
646 $page->assign('ok', true
);
647 $page->assign('yourself', S
::user()->displayName());
648 $page->assign('sexe', S
::user()->isFemale());
649 } else if (!S
::logged() && $user) {
650 Email
::activate_storage($user, 'imap', Bogo
::IMAP_DEFAULT
);
651 $page->assign('ok', true
);
652 $page->assign('yourself', $user->displayName());
653 $page->assign('sexe', $user->isFemale());
657 function handler_broken($page, $warn = null
, $email = null
)
659 require_once 'emails.inc.php';
660 $wp = new PlWikiPage('Xorg.PatteCassée');
665 $page->changeTpl('emails/broken.tpl');
667 if ($warn == 'warn' && $email) {
668 S
::assert_xsrf_token();
670 // Usual verifications.
671 $email = valide_email($email);
672 $uid = XDB
::fetchOneCell('SELECT uid
673 FROM email_redirect_account
674 WHERE redirect = {?}', $email);
677 $dest = User
::getWithUID($uid);
678 $active = XDB
::fetchOneCell('SELECT flags
679 FROM email_redirect_account
680 WHERE redirect = {?} AND uid = {?}', $email, $uid) == 'active';
682 $mail = new PlMailer('emails/broken-web.mail.tpl');
683 $mail->assign('email', $email);
684 $mail->assign('request', S
::user());
685 $mail->sendTo($dest);
686 $page->trigSuccess('Email envoyé !');
688 } elseif (Post
::has('email')) {
689 S
::assert_xsrf_token();
691 $email = Post
::t('email');
693 if (!User
::isForeignEmailAddress($email)) {
694 $page->assign('neuneu', true
);
696 $user = mark_broken_email($email);
697 $page->assign('user', $user);
698 $page->assign('email', $email);
703 function handler_duplicated($page, $action = 'list', $email = null
)
705 $page->changeTpl('emails/duplicated.tpl');
707 $states = array('pending' => 'En attente...',
708 'safe' => 'Pas d\'inquiétude',
709 'unsafe' => 'Recherches en cours',
710 'dangerous' => 'Usurpations par cette adresse');
711 $page->assign('states', $states);
713 if (Post
::has('action')) {
714 S
::assert_xsrf_token();
716 switch (Post
::v('action')) {
718 if (trim(Post
::v('emailN')) != '') {
719 Xdb
::execute('INSERT IGNORE INTO email_watch (email, state, detection, last, uid, description)
720 VALUES ({?}, {?}, CURDATE(), NOW(), {?}, {?})',
721 trim(Post
::v('emailN')), Post
::v('stateN'), S
::i('uid'), Post
::v('descriptionN'));
726 Xdb
::execute('UPDATE email_watch
727 SET state = {?}, last = NOW(), uid = {?}, description = {?}
728 WHERE email = {?}', Post
::v('stateN'), S
::i('uid'), Post
::v('descriptionN'), Post
::v('emailN'));
732 if ($action == 'delete' && !is_null($email)) {
733 Xdb
::execute('DELETE FROM email_watch WHERE email = {?}', $email);
736 if ($action != 'create' && $action != 'edit') {
739 $page->assign('action', $action);
741 if ($action == 'list') {
742 $it = XDB
::iterRow('SELECT w.email, w.detection, w.state, s.email AS forlife
743 FROM email_watch AS w
744 INNER JOIN email_redirect_account AS r ON (w.email = r.redirect)
745 INNER JOIN email_source_account AS s ON (s.uid = r.uid AND s.type = \'forlife\')
746 ORDER BY w.state, w.email, s.email');
750 while (list($email, $date, $state, $forlife) = $it->next()) {
751 if (count($props) == 0 ||
$props['mail'] != $email) {
752 if (count($props) > 0) {
755 $props = array('mail' => $email,
756 'detection' => $date,
758 'users' => array($forlife));
760 $props['users'][] = $forlife;
763 if (count($props) > 0) {
766 $page->assign('table', $table);
767 } elseif ($action == 'edit') {
768 $it = XDB
::iterRow('SELECT w.detection, w.state, w.last, w.description,
769 a.hruid AS edit, s.email AS forlife
770 FROM email_watch AS w
771 INNER JOIN email_redirect_account AS r ON (w.email = r.redirect)
772 INNER JOIN email_source_account AS s ON (s.uid = r.uid AND s.type = \'forlife\')
773 LEFT JOIN accounts AS a ON (w.uid = a.uid)
779 while (list($detection, $state, $last, $description, $edit, $forlife) = $it->next()) {
780 if (count($props) == 0) {
781 $props = array('mail' => $email,
782 'detection' => $detection,
785 'description' => $description,
787 'users' => array($forlife));
789 $props['users'][] = $forlife;
792 $page->assign('doublon', $props);
796 function handler_lost($page, $action = 'list', $email = null
)
798 $page->changeTpl('emails/lost.tpl');
800 $page->assign('lost_emails',
801 XDB
::iterator('SELECT a.uid, a.hruid, pd.promo
803 INNER JOIN account_types AS at ON (a.type = at.type)
804 LEFT JOIN email_redirect_account AS er ON (er.uid = a.uid AND er.flags = \'active\' AND er.broken_level < 3
805 AND er.type != \'imap\' AND er.type != \'homonym\')
806 LEFT JOIN account_profiles AS ap ON (ap.uid = a.uid AND FIND_IN_SET(\'owner\', ap.perms))
807 LEFT JOIN profile_display AS pd ON (ap.pid = pd.pid)
808 LEFT JOIN profiles AS p ON (ap.pid = p.pid)
809 WHERE a.state = \'active\' AND er.redirect IS NULL AND FIND_IN_SET(\'mail\', at.perms) AND p.deathdate IS NULL
811 ORDER BY pd.promo, a.hruid'));
814 function handler_broken_addr($page)
816 require_once 'emails.inc.php';
817 $page->changeTpl('emails/broken_addr.tpl');
819 if (Env
::has('sort_broken')) {
820 S
::assert_xsrf_token();
822 $list = trim(Env
::v('list'));
824 $page->trigError('La liste est vide.');
826 $valid_emails = array();
827 $invalid_emails = array();
828 $broken_list = explode("\n", $list);
830 foreach ($broken_list as $orig_email) {
831 $orig_email = trim($orig_email);
832 if ($orig_email != '') {
833 $email = valide_email($orig_email);
834 if (empty($email) ||
$email == '@') {
835 $invalid_emails[] = trim($orig_email) . ': invalid email';
836 } elseif (!in_array($email, $valid_emails)) {
837 $nb = XDB
::fetchOneCell('SELECT COUNT(*)
838 FROM email_redirect_account
839 WHERE redirect = {?}', $email);
841 $valid_emails[] = $email;
843 $invalid_emails[] = $orig_email . ': no such redirection';
849 $page->assign('valid_emails', $valid_emails);
850 $page->assign('invalid_emails', $invalid_emails);
854 if (Env
::has('process_broken')) {
855 S
::assert_xsrf_token();
857 $list = trim(Env
::v('list'));
859 $page->trigError('La liste est vide.');
861 require_once 'notifs.inc.php';
863 $broken_user_list = array();
864 $broken_user_email_count = array();
865 $broken_user_profiles = array();
866 $broken_list = explode("\n", $list);
869 foreach ($broken_list as $email) {
871 if ($user = mark_broken_email($email, true
)) {
872 $userobj = User
::getSilentWithUID($user['uid']);
874 if (is_null($userobj)) {
877 $profile = $userobj->profile();
878 if (is_null($profile)) {
881 if ($user['nb_mails'] > 0 && $user['notify']) {
882 $mail = new PlMailer('emails/broken.mail.tpl');
883 $mail->setTo($userobj);
884 $mail->assign('user', $user);
885 $mail->assign('email', $email);
888 WatchProfileUpdate
::register($profile, 'broken');
891 $pid = $profile->id();
892 if (!isset($broken_user_list[$pid])) {
893 $broken_user_list[$pid] = array($email);
895 $broken_user_list[$pid][] = $email;
897 $broken_user_email_count[$pid] = $user['nb_mails'];
898 $broken_user_profiles[$pid] = $profile;
901 XDB
::execute('UPDATE email_redirect_account
902 SET broken_level = broken_level - 1
903 WHERE flags = \'active\' AND broken_level > 1
904 AND DATE_ADD(last, INTERVAL 1 MONTH) < CURDATE()');
905 XDB
::execute('UPDATE email_redirect_account
907 WHERE flags = \'active\' AND broken_level = 1
908 AND DATE_ADD(last, INTERVAL 1 YEAR) < CURDATE()');
910 // Output the list of users with recently broken addresses,
911 // along with the count of valid redirections.
912 pl_cached_content_headers('text/x-csv', 1);
914 $csv = fopen('php://output', 'w');
915 fputcsv($csv, array('nom', 'promo', 'bounces', 'nbmails', 'url', 'corps', 'job', 'networking'), ';');
916 $corpsList = DirEnum
::getOptions(DirEnum
::CURRENTCORPS
);
917 foreach ($broken_user_list as $pid => $mails) {
918 $profile = $broken_user_profiles[$pid];
919 $current_corps = $profile->getCorpsName();
920 $jobs = $profile->getJobs();
921 $companies = array();
922 foreach ($jobs as $job) {
923 $companies[] = $job->company
->name
;
925 $networkings = $profile->getNetworking(Profile
::NETWORKING_ALL
);
926 $networking_list = array();
927 foreach ($networkings as $networking) {
928 $networking_list[] = $networking['address'];
930 fputcsv($csv, array($profile->fullName(), $profile->promo(),
931 join(',', $mails), $broken_user_email_count[$pid],
932 'https://www.polytechnique.org/marketing/broken/' . $profile->hrid(),
933 $current_corps, implode(',', $companies), implode(',', $networking_list)), ';');
942 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker fenc=utf-8: