Prepare db migration.
[platal.git] / modules / email.php
index 2e5e429..82bedd8 100644 (file)
@@ -1,6 +1,6 @@
 <?php
 /***************************************************************************
- *  Copyright (C) 2003-2009 Polytechnique.org                              *
+ *  Copyright (C) 2003-2010 Polytechnique.org                              *
  *  http://opensource.polytechnique.org/                                   *
  *                                                                         *
  *  This program is free software; you can redistribute it and/or modify   *
@@ -24,23 +24,24 @@ class EmailModule extends PLModule
     function handlers()
     {
         return array(
-            'emails' => $this->make_hook('emails', AUTH_COOKIE),
-            'emails/alias'    => $this->make_hook('alias', AUTH_MDP),
-            'emails/antispam' => $this->make_hook('antispam', AUTH_MDP),
-            'emails/broken'   => $this->make_hook('broken', AUTH_COOKIE),
-            'emails/redirect' => $this->make_hook('redirect', AUTH_MDP),
-            'emails/send'     => $this->make_hook('send', AUTH_MDP),
-            'emails/antispam/submit'  => $this->make_hook('submit', AUTH_COOKIE),
-            'emails/test'     => $this->make_hook('test', AUTH_COOKIE, 'user', NO_AUTH),
-
-            'emails/rewrite/in' => $this->make_hook('rewrite_in', AUTH_PUBLIC),
-            'emails/rewrite/out' => $this->make_hook('rewrite_out', AUTH_PUBLIC),
-
-            'emails/imap/in'  => $this->make_hook('imap_in', AUTH_PUBLIC),
-
-            'admin/emails/duplicated' => $this->make_hook('duplicated', AUTH_MDP, 'admin'),
-            'admin/emails/watch'      => $this->make_hook('duplicated', AUTH_MDP, 'admin'),
-            'admin/emails/lost'       => $this->make_hook('lost', AUTH_MDP, 'admin'),
+            'emails'                  => $this->make_hook('emails',      AUTH_COOKIE),
+            'emails/alias'            => $this->make_hook('alias',       AUTH_MDP),
+            'emails/antispam'         => $this->make_hook('antispam',    AUTH_MDP),
+            'emails/broken'           => $this->make_hook('broken',      AUTH_COOKIE),
+            'emails/redirect'         => $this->make_hook('redirect',    AUTH_MDP),
+            'emails/send'             => $this->make_hook('send',        AUTH_MDP),
+            'emails/antispam/submit'  => $this->make_hook('submit',      AUTH_COOKIE),
+            'emails/test'             => $this->make_hook('test',        AUTH_COOKIE, 'user', NO_AUTH),
+
+            'emails/rewrite/in'       => $this->make_hook('rewrite_in',  AUTH_PUBLIC),
+            'emails/rewrite/out'      => $this->make_hook('rewrite_out', AUTH_PUBLIC),
+
+            'emails/imap/in'          => $this->make_hook('imap_in',     AUTH_PUBLIC),
+
+            'admin/emails/duplicated' => $this->make_hook('duplicated',  AUTH_MDP,    'admin'),
+            'admin/emails/watch'      => $this->make_hook('duplicated',  AUTH_MDP,    'admin'),
+            'admin/emails/lost'       => $this->make_hook('lost',        AUTH_MDP,    'admin'),
+            'admin/emails/broken'     => $this->make_hook('broken_addr', AUTH_MDP,    'admin'),
         );
     }
 
@@ -226,8 +227,9 @@ class EmailModule extends PLModule
         $email = str_replace(' ', '+', $email);
 
         // Apply email redirection change requests.
+        $result = SUCCESS;
         if ($action == 'remove' && $email) {
-            $retour = $redirect->delete_email($email);
+            $result = $redirect->delete_email($email);
         }
 
         if ($action == 'active' && $email) {
@@ -253,19 +255,19 @@ class EmailModule extends PLModule
                 if ($new_email == "new@example.org") {
                     $new_email = Env::v('email_new');
                 }
-                $retour = $redirect->add_email($new_email);
-                if ($retour == ERROR_INVALID_EMAIL) {
+                $result = $redirect->add_email($new_email);
+                if ($result == ERROR_INVALID_EMAIL) {
                     $page->assign('email', $new_email);
                 }
-                $page->assign('retour', $retour);
+                $page->assign('retour', $result);
             } elseif (empty($actifs)) {
-                $retour = ERROR_INACTIVE_REDIRECTION;
+                $result = ERROR_INACTIVE_REDIRECTION;
             } elseif (is_array($actifs)) {
-                $retour = $redirect->modify_email($actifs, Env::v('emails_rewrite', Array()));
+                $result = $redirect->modify_email($actifs, Env::v('emails_rewrite', Array()));
             }
         }
 
-        switch ($retour) {
+        switch ($result) {
           case ERROR_INACTIVE_REDIRECTION:
             $page->trigError('Tu ne peux pas avoir aucune adresse de redirection active, sinon ton adresse '
                              . $user->forlifeEmail() . ' ne fonctionnerait plus.');
@@ -322,7 +324,8 @@ class EmailModule extends PLModule
 
         $page->changeTpl('emails/antispam.tpl');
 
-        $bogo = new Bogo(S::user());
+        $user = S::user();
+        $bogo = new Bogo($user);
         if (isset($statut_filtre)) {
             $bogo->change($statut_filtre + 0);
         }
@@ -418,14 +421,26 @@ class EmailModule extends PLModule
                 $to2  = getEmails(Env::v('to_contacts'));
                 $cc2  = getEmails(Env::v('cc_contacts'));
                 $txt  = str_replace('^M', '', Env::v('contenu'));
-                $to   = Env::v('to');
-                $subj = Env::v('sujet');
-                $from = Env::v('from');
-                $cc   = trim(Env::v('cc'));
-                $bcc  = trim(Env::v('bcc'));
-
+                $to   = str_replace(';', ',', Env::t('to'));
+                $subj = Env::t('sujet');
+                $from = Env::t('from');
+                $cc   = str_replace(';', ',', Env::t('cc'));
+                $bcc  = str_replace(';', ',', Env::t('bcc'));
+
+                $email_regex = '/^[a-z0-9.\-+_\$]+@([\-.+_]?[a-z0-9])+$/i';
+                foreach (explode(',', $to . ',' . $cc . ',' . $bcc) as $email) {
+                    $email = trim($email);
+                    if ($email != '' && !preg_match($email_regex, $email)) {
+                        $page->trigError("L'adresse email " . $email  . ' est erronée.');
+                        $error = true;
+                    }
+                }
                 if (empty($to) && empty($cc) && empty($to2) && empty($bcc) && empty($cc2)) {
                     $page->trigError("Indique au moins un destinataire.");
+                    $error = true;
+                }
+
+                if ($error) {
                     $page->assign('uploaded_f', PlUpload::listFilenames(S::user()->login(), 'emails.send'));
                 } else {
                     $mymail = new PlMailer();
@@ -489,7 +504,7 @@ class EmailModule extends PLModule
         }
 
         // Retrieves the User object for the test email recipient.
-        if (S::has_perms() && $hruid) {
+        if (S::admin() && $hruid) {
             $user = User::getSilent($hruid);
         } else {
             $user = S::user();
@@ -635,7 +650,7 @@ class EmailModule extends PLModule
                 $mail->assign('email', $email);
                 $mail->assign('request', S::user());
                 $mail->sendTo($dest);
-                $page->trigSuccess("Email envoyé !");
+                $page->trigSuccess('Email envoyé&nbsp;!');
             }
         } elseif (Post::has('email')) {
             S::assert_xsrf_token();
@@ -783,6 +798,151 @@ class EmailModule extends PLModule
                                              a.state = 'active'
                                    ORDER BY  a.hruid"));
     }
+
+    function handler_broken_addr(&$page)
+    {
+        require_once 'emails.inc.php';
+        $page->changeTpl('emails/broken_addr.tpl');
+
+        if (Env::has('sort_broken')) {
+            S::assert_xsrf_token();
+
+            $list = trim(Env::v('list'));
+            if ($list == '') {
+                $page->trigError('La liste est vide.');
+            } else {
+                $valid_emails = array();
+                $invalid_emails = array();
+                $broken_list = explode("\n", $list);
+                sort($broken_list);
+                foreach ($broken_list as $orig_email) {
+                    $orig_email = trim($orig_email);
+                    if ($orig_email != '') {
+                        $email = valide_email($orig_email);
+                        if (empty($email) || $email == '@') {
+                            $invalid_emails[] = trim($orig_email) . ': invalid email';
+                        } elseif (!in_array($email, $valid_emails)) {
+                            $res = XDB::query('SELECT  COUNT(*)
+                                                 FROM  emails
+                                                WHERE  email = {?}', $email);
+                            if ($res->fetchOneCell() > 0) {
+                                $valid_emails[] = $email;
+                            } else {
+                                $invalid_emails[] = "$orig_email: no such redirection";
+                            }
+                        }
+                    }
+                }
+
+                $page->assign('valid_emails', $valid_emails);
+                $page->assign('invalid_emails', $invalid_emails);
+            }
+        }
+
+        if (Env::has('process_broken')) {
+            S::assert_xsrf_token();
+
+            $list = trim(Env::v('list'));
+            if ($list == '') {
+                $page->trigError('La liste est vide.');
+            } else {
+                global $platal;
+
+                $broken_user_list = array();
+                $broken_list = explode("\n", $list);
+                sort($broken_list);
+                foreach ($broken_list as $orig_email) {
+                    $email = valide_email(trim($orig_email));
+                    if (empty($email) || $email == '@') {
+                        continue;
+                    }
+
+                    $sel = XDB::query(
+                        "SELECT  e1.uid, e1.panne != 0 AS panne, count(e2.uid) AS nb_mails,
+                                 acc.full_name, a.alias
+                           FROM  emails        AS e1
+                      LEFT JOIN  emails        AS e2 ON (e1.uid = e2.uid AND FIND_IN_SET('active', e2.flags)
+                                                         AND e1.email != e2.email)
+                     INNER JOIN  accounts      AS acc  ON (e1.uid = acc.uid)
+                     INNER JOIN  aliases       AS a  ON (acc.uid = a.id AND FIND_IN_SET('bestalias', a.flags))
+                          WHERE  e1.email = {?}
+                       GROUP BY  e1.uid", $email);
+
+                    if ($x = $sel->fetchOneAssoc()) {
+                        if (!$x['panne']) {
+                            XDB::execute('UPDATE  emails
+                                             SET  panne=NOW(), last=NOW(), panne_level = 1
+                                           WHERE  email = {?}',
+                                          $email);
+                        } else {
+                            XDB::execute('UPDATE  emails
+                                             SET  last = CURDATE(), panne_level = panne_level + 1
+                                           WHERE  email = {?}
+                                                  AND DATE_ADD(last, INTERVAL 14 DAY) < CURDATE()',
+                                         $email);
+                        }
+
+                        if (!empty($x['nb_mails'])) {
+                            $mail = new PlMailer('emails/broken.mail.tpl');
+                            $mail->addTo("\"{$x['full_name']}\" <{$x['alias']}@"
+                                         . $globals->mail->domain . '>');
+                            $mail->assign('x', $x);
+                            $mail->assign('email', $email);
+                            $mail->send();
+                        }
+
+                        if (!isset($broken_user_list[$x['alias']])) {
+                            $broken_user_list[$x['alias']] = array($email);
+                        } else {
+                            $broken_user_list[$x['alias']][] = $email;
+                        }
+                    }
+                }
+
+                XDB::execute("UPDATE  emails
+                                 SET  panne_level = panne_level - 1
+                               WHERE  flags = 'active' AND panne_level > 1
+                                      AND DATE_ADD(last, INTERVAL 1 MONTH) < CURDATE()");
+                XDB::execute("UPDATE  emails
+                                 SET  panne_level = 0
+                               WHERE  flags = 'active' AND panne_level = 1
+                                      AND DATE_ADD(last, INTERVAL 1 YEAR) < CURDATE()");
+
+                // Output the list of users with recently broken addresses,
+                // along with the count of valid redirections.
+                require_once 'notifs.inc.php';
+                pl_content_headers("text/x-csv");
+
+                $csv = fopen('php://output', 'w');
+                fputcsv($csv, array('nom', 'promo', 'alias', 'bounce', 'nbmails', 'url'), ';');
+                foreach ($broken_user_list as $alias => $mails) {
+                    $sel = Xdb::query(
+                        "SELECT  acc.uid, count(e.email) AS nb_mails,
+                                 IFNULL(pd.public_name, acc.full_name) AS fullname,
+                                 IFNULL(pd.promo, 0) AS promo,
+                           FROM  aliases    AS a
+                     INNER JOIN  accounts   AS acc ON a.id = acc.uid
+                      LEFT JOIN  emails     AS e ON (e.uid = acc.uid
+                                                        AND FIND_IN_SET('active', e.flags) AND e.panne = 0)
+                      LEFT JOIN  account_profiles AS ap ON (acc.uid = ap.uid AND FIND_IN_SET('owner', ap.perms))
+                      LEFT JOIN  profile_display AS pd ON (pd.pid = ap.pid)
+                          WHERE  a.alias = {?}
+                       GROUP BY  acc.uid", $alias);
+
+                    if ($x = $sel->fetchOneAssoc()) {
+                        if ($x['nb_mails'] == 0) {
+                            register_profile_update($x['user_id'], 'broken');
+                        }
+                        fputcsv($csv, array($x['fullname'], $x['promo'], $alias,
+                                            join(',', $mails), $x['nb_mails'],
+                                            'https://www.polytechnique.org/marketing/broken/' . $alias), ';');
+                    }
+                }
+                fclose($csv);
+                exit;
+            }
+        }
+    }
 }
 
 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8: