2 /***************************************************************************
3 * Copyright (C) 2003-2011 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'),
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",
103 $page->assign('aliases', $aliases);
105 $alias = XDB
::fetchOneCell('SELECT COUNT(email)
106 FROM email_source_account
107 WHERE uid = {?} AND type = \'alias_aux\'',
109 $page->assign('alias', $alias);
112 // Check for homonyms.
113 $page->assign('homonyme', $user->homonyme
);
115 // Display active redirections.
116 $redirect = new Redirect($user);
117 $page->assign('mails', $redirect->active_emails());
119 // User's mail domains.
120 $mail_domains = array($user->alternateEmailDomain());
121 $mail_domains[] = User
::$sub_mail_domains['all'] . $globals->mail
->domain
;
122 $mail_domains[] = User
::$sub_mail_domains['all'] . $globals->mail
->domain2
;
123 $page->assign('main_email_domain', $user->mainEmailDomain());
124 $page->assign('mail_domains', $mail_domains);
127 function handler_alias($page, $action = null
, $value = null
)
131 $page->changeTpl('emails/alias.tpl');
132 $page->setTitle('Alias melix.net');
135 $page->assign('request', AliasReq
::get_request($user->id()));
137 // Remove the email alias.
138 if ($action == 'delete') {
139 S
::assert_xsrf_token();
141 XDB
::execute('DELETE FROM email_source_account
142 WHERE uid = {?} AND type = \'alias_aux\'',
145 require_once 'emails.inc.php';
146 fix_bestalias($user);
149 // Fetch existing auxiliary aliases.
150 list($alias, $old_alias) = XDB
::fetchOneRow('SELECT CONCAT(s.email, \'@\', d.name), s.email
151 FROM email_source_account AS s
152 INNER JOIN email_virtual_domains AS d ON (s.domain = d.id)
153 WHERE s.uid = {?} AND s.type = \'alias_aux\'',
155 $visibility = $user->hasProfile() && $user->profile()->isVisible($user->profile()->alias_pub
);
156 $page->assign('current', $alias);
157 $page->assign('user', $user);
158 $page->assign('mail_public', $visibility);
160 if ($action == 'ask' && Env
::has('alias') && Env
::has('reason')) {
161 S
::assert_xsrf_token();
163 // Retrieves user request.
164 $new_alias = Env
::v('alias');
165 $reason = Env
::v('reason');
166 $public = (Env
::v('public', 'off') == 'on') ?
'private' : 'hidden';
168 $page->assign('r_alias', $new_alias);
169 $page->assign('r_reason', $reason);
170 if ($public == 'private') {
171 $page->assign('r_public', true
);
174 // Checks special charaters in alias.
175 if (!preg_match("/^[a-zA-Z0-9\-.]{2,19}[a-zA-Z0-9\-]$/", $new_alias)) {
176 $page->trigError("L'adresse demandée n'est pas valide."
177 . " Vérifie qu'elle comporte entre 3 et 20 caractères"
178 . " et qu'elle ne contient que des lettres non accentuées,"
179 . " des chiffres ou les caractères '-' et '.'. De plus, elle ne"
180 . " peut pas se terminer par un point.");
183 // Checks if the alias has already been given.
184 $res = XDB
::query('SELECT COUNT(email)
185 FROM email_source_account
186 WHERE email = {?} AND type = \'alias_aux\'',
188 if ($res->fetchOneCell() > 0) {
189 $page->trigError("L'alias $new_alias a déja été attribué. Tu ne peux donc pas l'obtenir.");
193 // Checks if the alias has already been asked for.
194 $it = Validate
::iterate('alias');
195 while($req = $it->next()) {
196 if ($req->alias
== $new_alias) {
197 $page->trigError("L'alias $new_alias a déja été demandé. Tu ne peux donc pas l'obtenir pour l'instant.");
202 // Sends requests. This will erase any previous alias pending request.
203 $myalias = new AliasReq($user, $new_alias, $reason, $public, $old_alias);
205 $page->assign('success', $new_alias);
208 } elseif ($action == 'set' && ($value == 'public' ||
$value == 'private')) {
209 if (!S
::has_xsrf_token()) {
213 if ($user->hasProfile()) {
214 XDB
::execute('UPDATE profiles
217 $value, $user->profile()->id());
223 function handler_redirect($page, $action = null
, $email = null
, $rewrite = null
)
226 require_once 'emails.inc.php';
228 $page->changeTpl('emails/redirect.tpl');
231 $page->assign_by_ref('user', $user);
232 $page->assign('eleve', $user->promo() >= date("Y") - 5);
234 $redirect = new Redirect($user);
236 // FS#703 : $_GET is urldecoded twice, hence
237 // + (the data) => %2B (in the url) => + (first decoding) => ' ' (second decoding)
238 // Since there can be no spaces in emails, we can fix this with :
239 $email = str_replace(' ', '+', $email);
241 // Apply email redirection change requests.
243 if ($action == 'remove' && $email) {
244 $result = $redirect->delete_email($email);
247 if ($action == 'active' && $email) {
248 $redirect->modify_one_email($email, true
);
251 if ($action == 'inactive' && $email) {
252 $redirect->modify_one_email($email, false
);
255 if ($action == 'rewrite' && $email) {
256 $redirect->modify_one_email_redirect($email, $rewrite);
259 if (Env
::has('emailop')) {
260 S
::assert_xsrf_token();
262 $actifs = Env
::v('emails_actifs', array());
263 if (Env
::v('emailop') == "ajouter" && Env
::has('email')) {
264 $error_email = false
;
265 $new_email = Env
::v('email');
266 if ($new_email == "new@example.org") {
267 $new_email = Env
::v('email_new');
269 $result = $redirect->add_email($new_email);
270 if ($result == ERROR_INVALID_EMAIL
) {
272 $page->assign('email', $new_email);
274 $page->assign('retour', $result);
275 $page->assign('error_email', $error_email);
276 } elseif (empty($actifs)) {
277 $result = ERROR_INACTIVE_REDIRECTION
;
278 } elseif (is_array($actifs)) {
279 $result = $redirect->modify_email($actifs, Env
::v('emails_rewrite', array()));
284 case ERROR_INACTIVE_REDIRECTION
:
285 $page->trigError('Tu ne peux pas avoir aucune adresse de redirection active, sinon ton adresse '
286 . $user->forlifeEmail() . ' ne fonctionnerait plus.');
288 case ERROR_INVALID_EMAIL
:
289 $page->trigError('Erreur : l\'email n\'est pas valide.');
291 case ERROR_LOOP_EMAIL
:
292 $page->trigError('Erreur : ' . $user->forlifeEmail()
293 . ' ne doit pas être renvoyé vers lui-même, ni vers son équivalent en '
294 . $globals->mail
->domain2
. ' ni vers polytechnique.edu.');
297 // Fetch existing email aliases.
298 $alias = XDB
::query('SELECT CONCAT(s.email, \'@\', d.name) AS email, s.expire
299 FROM email_source_account AS s
300 INNER JOIN email_virtual_domains AS m ON (s.domain = m.id)
301 INNER JOIN email_virtual_domains AS d ON (m.id = d.aliasing)
303 ORDER BY NOT(s.type = \'alias_aux\'), s.email, d.name',
305 $page->assign('alias', $alias->fetchAllAssoc());
306 $page->assign('best_email', $user->bestEmail());
308 $page->assign('emails', $redirect->emails
);
310 // Display GoogleApps acount information.
311 require_once 'googleapps.inc.php';
312 $page->assign('googleapps', GoogleAppsAccount
::account_status($user->id()));
314 require_once 'emails.combobox.inc.php';
315 fill_email_combobox($page, array('job', 'stripped_directory'));
318 function handler_antispam($page, $filter_status = null
, $redirection = null
)
320 require_once 'emails.inc.php';
321 $wp = new PlWikiPage('Xorg.Antispam');
324 $page->changeTpl('emails/antispam.tpl');
327 $bogo = new Bogo($user);
328 if (!is_null($filter_status)) {
329 if (is_null($redirection)) {
330 $bogo->changeAll($filter_status);
332 $bogo->change($redirection, $filter_status);
335 $page->assign('filter', $bogo->state
);
336 $page->assign('single_state', $bogo->single_state
);
337 $page->assign('single_redirection', $bogo->single_redirection
);
338 $page->assign('redirections', $bogo->redirections
);
341 function handler_submit($page)
343 $wp = new PlWikiPage('Xorg.Mails');
345 $page->changeTpl('emails/submit_spam.tpl');
347 if (Post
::has('send_email')) {
348 S
::assert_xsrf_token();
350 $upload = PlUpload
::get($_FILES['mail'], S
::user()->login(), 'spam.submit', true
);
352 $page->trigError('Une erreur a été rencontrée lors du transfert du fichier');
355 $mime = $upload->contentType();
356 if ($mime != 'text/x-mail' && $mime != 'message/rfc822') {
358 $page->trigError('Le fichier ne contient pas un email complet');
361 $type = (Post
::v('type') == 'spam' ?
'spam' : 'nonspam');
364 $box = $type . '@' . $globals->mail
->domain
;
365 $mailer = new PlMailer();
366 $mailer->addTo($box);
367 $mailer->setFrom('"' . S
::user()->fullName() . '" <web@' . $globals->mail
->domain
. '>');
368 $mailer->setTxtBody($type . ' soumis par ' . S
::user()->login() . ' via le web');
369 $mailer->addUploadAttachment($upload, $type . '.mail');
371 $page->trigSuccess('Le message a été transmis à ' . $box);
376 function handler_send($page)
378 $page->changeTpl('emails/send.tpl');
380 $page->setTitle('Envoyer un email');
382 // action si on recoit un formulaire
383 if (Post
::has('save')) {
384 if (!S
::has_xsrf_token()) {
388 unset($_POST['save']);
389 if (trim(preg_replace('/-- .*/', '', Post
::v('contenu'))) != "") {
390 Post
::set('to_contacts', explode(';', Post
::s('to_contacts')));
391 Post
::set('cc_contacts', explode(';', Post
::s('cc_contacts')));
392 $data = serialize($_POST);
393 XDB
::execute('INSERT INTO email_send_save (uid, data)
395 ON DUPLICATE KEY UPDATE data = VALUES(data)',
396 S
::user()->id('uid'), $data);
399 } else if (Env
::v('submit') == 'Envoyer') {
400 S
::assert_xsrf_token();
402 function getEmails($aliases)
404 if (!is_array($aliases)) {
407 $uf = new UserFilter(new UFC_Hrpid($aliases));
408 $users = $uf->iterUsers();
410 while ($user = $users->next()) {
411 $ret[] = $user->forlife
;
413 return join(', ', $ret);
417 foreach ($_FILES as &$file) {
418 if ($file['name'] && !PlUpload
::get($file, S
::user()->login(), 'emails.send', false
)) {
419 $page->trigError(PlUpload
::$lastError);
426 XDB
::execute("DELETE FROM email_send_save
430 $to2 = getEmails(Env
::v('to_contacts'));
431 $cc2 = getEmails(Env
::v('cc_contacts'));
432 $txt = str_replace('^M', '', Env
::v('contenu'));
433 $to = str_replace(';', ',', Env
::t('to'));
434 $subj = Env
::t('sujet');
435 $from = Env
::t('from');
436 $cc = str_replace(';', ',', Env
::t('cc'));
437 $bcc = str_replace(';', ',', Env
::t('bcc'));
439 $email_regex = '/^[a-z0-9.\-+_\$]+@([\-.+_]?[a-z0-9])+$/i';
440 foreach (explode(',', $to . ',' . $cc . ',' . $bcc) as $email) {
441 $email = trim($email);
442 if ($email != '' && !preg_match($email_regex, $email)) {
443 $page->trigError("L'adresse email " . $email . ' est erronée.');
447 if (empty($to) && empty($cc) && empty($to2) && empty($bcc) && empty($cc2)) {
448 $page->trigError("Indique au moins un destinataire.");
453 $page->assign('uploaded_f', PlUpload
::listFilenames(S
::user()->login(), 'emails.send'));
455 $mymail = new PlMailer();
456 $mymail->setFrom($from);
457 $mymail->setSubject($subj);
458 if (!empty($to)) { $mymail->addTo($to); }
459 if (!empty($cc)) { $mymail->addCc($cc); }
460 if (!empty($bcc)) { $mymail->addBcc($bcc); }
461 if (!empty($to2)) { $mymail->addTo($to2); }
462 if (!empty($cc2)) { $mymail->addCc($cc2); }
463 $files =& PlUpload
::listFiles(S
::user()->login(), 'emails.send');
464 foreach ($files as $name=>&$upload) {
465 $mymail->addUploadAttachment($upload, $name);
467 if (Env
::v('wiki') == 'text') {
468 $mymail->setTxtBody(wordwrap($txt, 78, "\n"));
470 $mymail->setWikiBody($txt);
472 if ($mymail->send()) {
473 $page->trigSuccess("Ton email a bien été envoyé.");
474 $_REQUEST = array('bcc' => S
::user()->bestEmail());
475 PlUpload
::clear(S
::user()->login(), 'emails.send');
477 $page->trigError("Erreur lors de l'envoi du courriel, réessaye.");
478 $page->assign('uploaded_f', PlUpload
::listFilenames(S
::user()->login(), 'emails.send'));
483 $res = XDB
::query("SELECT data
485 WHERE uid = {?}", S
::i('uid'));
486 if ($res->numRows() == 0) {
487 PlUpload
::clear(S
::user()->login(), 'emails.send');
488 $_REQUEST['bcc'] = S
::user()->bestEmail();
490 $data = unserialize($res->fetchOneCell());
491 $_REQUEST = array_merge($_REQUEST, $data);
495 $uf = new UserFilter(new PFC_And(new UFC_Contact(S
::user()),
496 new UFC_Registered()),
497 UserFilter
::sortByName());
498 $contacts = $uf->getProfiles();
499 $page->assign('contacts', $contacts);
500 $page->assign('maxsize', ini_get('upload_max_filesize') . 'o');
501 $page->assign('user', S
::user());
502 $preferences = XDB
::fetchOneAssoc('SELECT from_email, from_format
506 if ($preferences['from_email'] == '') {
507 $preferences['from_email'] = '"' . S
::user()->fullName() . '" <' . S
::user()->bestEmail() . '>';
509 $page->assign('preferences', $preferences);
512 function handler_test($page, $hruid = null
)
514 require_once 'emails.inc.php';
516 if (!S
::has_xsrf_token()) {
520 // Retrieves the User object for the test email recipient.
521 if (S
::admin() && $hruid) {
522 $user = User
::getSilent($hruid);
530 // Sends the test email.
531 $redirect = new Redirect($user);
533 $mailer = new PlMailer('emails/test.mail.tpl');
534 $mailer->assign('email', $user->bestEmail());
535 $mailer->assign('redirects', $redirect->active_emails());
536 $mailer->assign('display_name', $user->displayName());
537 $mailer->assign('sexe', $user->isFemale());
538 $mailer->send($user->isEmailFormatHtml());
542 function handler_rewrite_in($page, $mail, $hash)
544 $page->changeTpl('emails/rewrite.tpl');
545 $page->assign('option', 'in');
546 if (empty($mail) ||
empty($hash)) {
549 $pos = strrpos($mail, '_');
550 if ($pos === false
) {
554 $res = XDB
::query('SELECT COUNT(*)
555 FROM email_redirect_account
556 WHERE redirect = {?} AND hash = {?} AND type = \'smtp\'',
558 $count = intval($res->fetchOneCell());
560 XDB
::query('UPDATE email_redirect_account
561 SET allow_rewrite = true, hash = NULL
562 WHERE redirect = {?} AND hash = {?} AND type = \'smtp\'',
564 $page->trigSuccess("Réécriture activée pour l'adresse " . $mail);
570 function handler_rewrite_out($page, $mail, $hash)
572 $page->changeTpl('emails/rewrite.tpl');
573 $page->assign('option', 'out');
574 if (empty($mail) ||
empty($hash)) {
577 $pos = strrpos($mail, '_');
578 if ($pos === false
) {
582 $res = XDB
::query('SELECT COUNT(*)
583 FROM email_redirect_account
584 WHERE redirect = {?} AND hash = {?} AND type = \'smtp\'',
586 $count = intval($res->fetchOneCell());
589 $res = XDB
::query('SELECT e.redirect, e.rewrite, a.hruid
590 FROM email_redirect_account AS e
591 INNER JOIN accounts AS a ON (e.uid = a.uid)
592 WHERE e.redirect = {?} AND e.hash = {?}',
594 XDB
::query('UPDATE email_redirect_account
595 SET allow_rewrite = false, hash = NULL
596 WHERE redirect = {?} AND hash = {?}',
598 list($mail, $rewrite, $hruid) = $res->fetchOneRow();
599 $mail = new PlMailer();
600 $mail->setFrom("webmaster@" . $globals->mail
->domain
);
601 $mail->addTo("support@" . $globals->mail
->domain
);
602 $mail->setSubject("Tentative de détournement de correspondance via le rewrite");
603 $mail->setTxtBody("$hruid a tenté un rewrite de $mail vers $rewrite. Cette demande a été rejetée via le web");
605 $page->trigWarning("Un mail d'alerte a été envoyé à l'équipe de " . $globals->core
->sitename
);
611 function handler_imap_in($page, $hash = null
, $login = null
)
613 $page->changeTpl('emails/imap_register.tpl');
615 if (!empty($hash) ||
!empty($login)) {
616 $user = User
::getSilent($login);
618 $req = XDB
::query('SELECT 1
620 WHERE uid = {?} AND hash = {?}',
622 if ($req->numRows() == 0) {
628 require_once 'emails.inc.php';
629 $page->assign('ok', false
);
630 if (S
::logged() && (is_null($user) ||
$user->id() == S
::i('uid'))) {
631 Email
::activate_storage(S
::user(), 'imap', Bogo
::IMAP_DEFAULT
);
632 $page->assign('ok', true
);
633 $page->assign('yourself', S
::user()->displayName());
634 $page->assign('sexe', S
::user()->isFemale());
635 } else if (!S
::logged() && $user) {
636 Email
::activate_storage($user, 'imap', Bogo
::IMAP_DEFAULT
);
637 $page->assign('ok', true
);
638 $page->assign('yourself', $user->displayName());
639 $page->assign('sexe', $user->isFemale());
643 function handler_broken($page, $warn = null
, $email = null
)
645 require_once 'emails.inc.php';
646 $wp = new PlWikiPage('Xorg.PatteCassée');
651 $page->changeTpl('emails/broken.tpl');
653 if ($warn == 'warn' && $email) {
654 S
::assert_xsrf_token();
656 // Usual verifications.
657 $email = valide_email($email);
658 $uid = XDB
::fetchOneCell('SELECT uid
659 FROM email_redirect_account
660 WHERE redirect = {?}', $email);
663 $dest = User
::getWithUID($uid);
665 $mail = new PlMailer('emails/broken-web.mail.tpl');
666 $mail->assign('email', $email);
667 $mail->assign('request', S
::user());
668 $mail->sendTo($dest);
669 $page->trigSuccess('Email envoyé !');
671 } elseif (Post
::has('email')) {
672 S
::assert_xsrf_token();
674 $email = Post
::t('email');
676 if (!User
::isForeignEmailAddress($email)) {
677 $page->assign('neuneu', true
);
679 $user = mark_broken_email($email);
680 $page->assign('user', $user);
681 $page->assign('email', $email);
686 function handler_duplicated($page, $action = 'list', $email = null
)
688 $page->changeTpl('emails/duplicated.tpl');
690 $states = array('pending' => 'En attente...',
691 'safe' => 'Pas d\'inquiétude',
692 'unsafe' => 'Recherches en cours',
693 'dangerous' => 'Usurpations par cette adresse');
694 $page->assign('states', $states);
696 if (Post
::has('action')) {
697 S
::assert_xsrf_token();
699 switch (Post
::v('action')) {
701 if (trim(Post
::v('emailN')) != '') {
702 Xdb
::execute('INSERT IGNORE INTO email_watch (email, state, detection, last, uid, description)
703 VALUES ({?}, {?}, CURDATE(), NOW(), {?}, {?})',
704 trim(Post
::v('emailN')), Post
::v('stateN'), S
::i('uid'), Post
::v('descriptionN'));
709 Xdb
::execute('UPDATE email_watch
710 SET state = {?}, last = NOW(), uid = {?}, description = {?}
711 WHERE email = {?}', Post
::v('stateN'), S
::i('uid'), Post
::v('descriptionN'), Post
::v('emailN'));
715 if ($action == 'delete' && !is_null($email)) {
716 Xdb
::execute('DELETE FROM email_watch WHERE email = {?}', $email);
719 if ($action != 'create' && $action != 'edit') {
722 $page->assign('action', $action);
724 if ($action == 'list') {
725 $it = XDB
::iterRow('SELECT w.email, w.detection, w.state, s.email AS forlife
726 FROM email_watch AS w
727 INNER JOIN email_redirect_account AS r ON (w.email = r.redirect)
728 INNER JOIN email_source_account AS s ON (s.uid = r.uid AND s.type = \'forlife\')
729 ORDER BY w.state, w.email, s.email');
733 while (list($email, $date, $state, $forlife) = $it->next()) {
734 if (count($props) == 0 ||
$props['mail'] != $email) {
735 if (count($props) > 0) {
738 $props = array('mail' => $email,
739 'detection' => $date,
741 'users' => array($forlife));
743 $props['users'][] = $forlife;
746 if (count($props) > 0) {
749 $page->assign('table', $table);
750 } elseif ($action == 'edit') {
751 $it = XDB
::iterRow('SELECT w.detection, w.state, w.last, w.description,
752 a.hruid AS edit, s.email AS forlife
753 FROM email_watch AS w
754 INNER JOIN email_redirect_account AS r ON (w.email = r.redirect)
755 INNER JOIN email_source_account AS s ON (s.uid = r.uid AND s.type = \'forlife\')
756 LEFT JOIN accounts AS a ON (w.uid = a.uid)
762 while (list($detection, $state, $last, $description, $edit, $forlife) = $it->next()) {
763 if (count($props) == 0) {
764 $props = array('mail' => $email,
765 'detection' => $detection,
768 'description' => $description,
770 'users' => array($forlife));
772 $props['users'][] = $forlife;
775 $page->assign('doublon', $props);
779 function handler_lost($page, $action = 'list', $email = null
)
781 $page->changeTpl('emails/lost.tpl');
783 $page->assign('lost_emails',
784 XDB
::iterator('SELECT a.uid, a.hruid, pd.promo
786 INNER JOIN account_types AS at ON (a.type = at.type)
787 LEFT JOIN email_redirect_account AS er ON (er.uid = a.uid AND er.flags = \'active\' AND er.broken_level < 3
788 AND er.type != \'imap\' AND er.type != \'homonym\')
789 LEFT JOIN account_profiles AS ap ON (ap.uid = a.uid AND FIND_IN_SET(\'owner\', ap.perms))
790 LEFT JOIN profile_display AS pd ON (ap.pid = pd.pid)
791 WHERE a.state = \'active\' AND er.redirect IS NULL AND FIND_IN_SET(\'mail\', at.perms)
793 ORDER BY pd.promo, a.hruid'));
796 function handler_broken_addr($page)
798 require_once 'emails.inc.php';
799 $page->changeTpl('emails/broken_addr.tpl');
801 if (Env
::has('sort_broken')) {
802 S
::assert_xsrf_token();
804 $list = trim(Env
::v('list'));
806 $page->trigError('La liste est vide.');
808 $valid_emails = array();
809 $invalid_emails = array();
810 $broken_list = explode("\n", $list);
812 foreach ($broken_list as $orig_email) {
813 $orig_email = trim($orig_email);
814 if ($orig_email != '') {
815 $email = valide_email($orig_email);
816 if (empty($email) ||
$email == '@') {
817 $invalid_emails[] = trim($orig_email) . ': invalid email';
818 } elseif (!in_array($email, $valid_emails)) {
819 $nb = XDB
::fetchOneCell('SELECT COUNT(*)
820 FROM email_redirect_account
821 WHERE redirect = {?}', $email);
823 $valid_emails[] = $email;
825 $invalid_emails[] = $orig_email . ': no such redirection';
831 $page->assign('valid_emails', $valid_emails);
832 $page->assign('invalid_emails', $invalid_emails);
836 if (Env
::has('process_broken')) {
837 S
::assert_xsrf_token();
839 $list = trim(Env
::v('list'));
841 $page->trigError('La liste est vide.');
843 require_once 'notifs.inc.php';
845 $broken_user_list = array();
846 $broken_user_email_count = array();
847 $broken_list = explode("\n", $list);
850 foreach ($broken_list as $email) {
851 if ($user = mark_broken_email($email, true
)) {
852 if ($user['nb_mails'] > 0 && $user['notify']) {
853 $mail = new PlMailer('emails/broken.mail.tpl');
854 $dest = User
::getSilentWithUID($user['uid']);
856 $mail->assign('user', $user);
857 $mail->assign('email', $email);
860 $profile = Profile
::get($user['alias']);
861 WatchProfileUpdate
::register($profile, 'broken');
864 if (!isset($broken_user_list[$user['uid']])) {
865 $broken_user_list[$user['uid']] = array($email);
867 $broken_user_list[$user['uid']][] = $email;
869 $broken_user_email_count[$user['uid']] = $user['nb_mails'];
873 XDB
::execute('UPDATE email_redirect_account
874 SET broken_level = broken_level - 1
875 WHERE flags = \'active\' AND broken_level > 1
876 AND DATE_ADD(last, INTERVAL 1 MONTH) < CURDATE()');
877 XDB
::execute('UPDATE email_redirect_account
879 WHERE flags = \'active\' AND broken_level = 1
880 AND DATE_ADD(last, INTERVAL 1 YEAR) < CURDATE()');
882 // Output the list of users with recently broken addresses,
883 // along with the count of valid redirections.
884 pl_cached_content_headers('text/x-csv', 1);
886 $csv = fopen('php://output', 'w');
887 fputcsv($csv, array('nom', 'promo', 'bounces', 'nbmails', 'url', 'corps', 'job', 'networking'), ';');
888 $corpsList = DirEnum
::getOptions(DirEnum
::CURRENTCORPS
);
889 foreach ($broken_user_list as $uid => $mails) {
890 $profile = Profile
::get($uid);
891 $corps = $profile->getCorps();
892 $current_corps = ($corps && $corps->current
) ?
$corpsList[$corps->current
] : '';
893 $jobs = $profile->getJobs();
894 $companies = array();
895 foreach ($jobs as $job) {
896 $companies[] = $job->company
->name
;
898 $networkings = $profile->getNetworking(Profile
::NETWORKING_ALL
);
899 $networking_list = array();
900 foreach ($networkings as $networking) {
901 $networking_list[] = $networking['address'];
903 fputcsv($csv, array($profile->fullName(), $profile->promo(),
904 join(',', $mails), $broken_user_email_count[$uid],
905 'https://www.polytechnique.org/marketing/broken/' . $profile->hrid(),
906 $current_corps, implode(',', $companies), implode(',', $networking_list)), ';');
915 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: