Moving to GitHub.
[platal.git] / modules / xnetlists.php
index 1c59e10..bc1bcbb 100644 (file)
@@ -1,6 +1,6 @@
 <?php
 /***************************************************************************
- *  Copyright (C) 2003-2008 Polytechnique.org                              *
+ *  Copyright (C) 2003-2014 Polytechnique.org                              *
  *  http://opensource.polytechnique.org/                                   *
  *                                                                         *
  *  This program is free software; you can redistribute it and/or modify   *
@@ -23,110 +23,127 @@ Platal::load('lists');
 
 class XnetListsModule extends ListsModule
 {
-    var $client;
-
     function handlers()
     {
         return array(
-            '%grp/lists'           => $this->make_hook('lists',     AUTH_MDP, 'groupmember'),
-            '%grp/lists/create'    => $this->make_hook('create',    AUTH_MDP, 'groupmember'),
+            '%grp/lists'              => $this->make_hook('lists',    AUTH_PASSWD, 'groupmember'),
+            '%grp/lists/create'       => $this->make_hook('create',   AUTH_PASSWD, 'groupmember'),
 
-            '%grp/lists/members'   => $this->make_hook('members',   AUTH_COOKIE),
-            '%grp/lists/csv'       => $this->make_hook('csv',       AUTH_COOKIE),
-            '%grp/lists/annu'      => $this->make_hook('annu',      AUTH_COOKIE),
-            '%grp/lists/archives'  => $this->make_hook('archives',  AUTH_COOKIE),
-            '%grp/lists/archives/rss' => $this->make_hook('rss',    AUTH_PUBLIC),
+            '%grp/lists/members'      => $this->make_hook('members',  AUTH_COOKIE, 'groups'),
+            '%grp/lists/csv'          => $this->make_hook('csv',      AUTH_COOKIE, 'groups'),
+            '%grp/lists/annu'         => $this->make_hook('annu',     AUTH_COOKIE, 'groups'),
+            '%grp/lists/archives'     => $this->make_hook('archives', AUTH_COOKIE, 'groups'),
+            '%grp/lists/archives/rss' => $this->make_hook('rss',      AUTH_PUBLIC),
 
-            '%grp/lists/moderate'  => $this->make_hook('moderate',  AUTH_MDP),
-            '%grp/lists/admin'     => $this->make_hook('admin',     AUTH_MDP),
-            '%grp/lists/options'   => $this->make_hook('options',   AUTH_MDP),
-            '%grp/lists/delete'    => $this->make_hook('delete',    AUTH_MDP),
+            '%grp/lists/moderate'     => $this->make_hook('moderate', AUTH_PASSWD, 'groups'),
+            '%grp/lists/admin'        => $this->make_hook('admin',    AUTH_PASSWD, 'groups'),
+            '%grp/lists/options'      => $this->make_hook('options',  AUTH_PASSWD, 'groups'),
+            '%grp/lists/delete'       => $this->make_hook('delete',   AUTH_PASSWD, 'groups'),
 
-            '%grp/lists/soptions'  => $this->make_hook('soptions',  AUTH_MDP),
-            '%grp/lists/check'     => $this->make_hook('check',     AUTH_MDP),
-            '%grp/lists/sync'      => $this->make_hook('sync',      AUTH_MDP),
+            '%grp/lists/soptions'     => $this->make_hook('soptions', AUTH_PASSWD, 'groups'),
+            '%grp/lists/check'        => $this->make_hook('check',    AUTH_PASSWD, 'groups'),
+            '%grp/lists/sync'         => $this->make_hook('sync',     AUTH_PASSWD, 'groups'),
 
-            '%grp/alias/admin'     => $this->make_hook('aadmin',    AUTH_MDP, 'groupadmin'),
-            '%grp/alias/create'    => $this->make_hook('acreate',   AUTH_MDP, 'groupadmin'),
+            '%grp/alias/admin'        => $this->make_hook('aadmin',   AUTH_PASSWD, 'groupadmin'),
+            '%grp/alias/create'       => $this->make_hook('acreate',  AUTH_PASSWD, 'groupadmin'),
 
             /* hack: lists uses that */
-            'profile' => $this->make_hook('profile', AUTH_PUBLIC),
+            'profile'                 => $this->make_hook('profile',  AUTH_PUBLIC),
         );
     }
 
-    function prepare_client(&$page, $user = null)
+    protected function get_lists_domain()
     {
         global $globals;
-        Platal::load('lists', 'lists.inc.php');
-
-        if (is_null($user)) {
-            $user =& S::user();
-        }
-        $this->client = new MMList($user, $globals->asso('mail_domain'));
-
-        $page->assign('asso', $globals->asso());
-        $page->setType($globals->asso('cat'));
-
         return $globals->asso('mail_domain');
     }
 
-    function handler_lists(&$page)
+    function handler_lists($page, $order_by = null, $order = null)
     {
-        global $globals;
+        require_once 'emails.inc.php';
 
-        if (!$globals->asso('mail_domain')) {
+        if (!$this->get_lists_domain()) {
             return PL_NOT_FOUND;
         }
-        $this->prepare_client($page);
         $page->changeTpl('xnetlists/index.tpl');
 
         if (Get::has('del')) {
             S::assert_xsrf_token();
-            $this->client->unsubscribe(Get::v('del'));
+            $mlist = $this->prepare_list(Get::v('del'));
+            $mlist->unsubscribe();
             pl_redirect('lists');
         }
         if (Get::has('add')) {
             S::assert_xsrf_token();
-            $this->client->subscribe(Get::v('add'));
+            $mlist = $this->prepare_list(Get::v('add'));
+            $mlist->subscribe();
             pl_redirect('lists');
         }
 
         if (Post::has('del_alias') && may_update()) {
             S::assert_xsrf_token();
 
-            $alias = Post::v('del_alias');
-            // prevent group admin from erasing aliases from other groups
-            $alias = substr($alias, 0, strpos($alias, '@')).'@'.$globals->asso('mail_domain');
-            XDB::query(
-                    'DELETE FROM  r, v
-                           USING  x4dat.virtual AS v
-                       LEFT JOIN  x4dat.virtual_redirect AS r USING(vid)
-                           WHERE  v.alias={?}', $alias);
-            $page->trigSuccess(Post::v('del_alias')." supprimé !");
+            $alias = Post::t('del_alias');
+            list($local_part, ) = explode('@', $alias);
+            delete_list_alias($local_part, $this->get_lists_domain());
+            $page->trigSuccess($alias . ' supprimé&nbsp;!');
         }
 
-        $listes = $this->client->get_lists();
-        $page->assign('listes',$listes);
+        $client = $this->prepare_client();
+        $listes = $client->get_lists();
+        // Default ordering is by ascending names.
+        if (is_null($order_by) || is_null($order)
+            || !in_array($order_by, array('list', 'desc', 'nbsub'))
+            || !in_array($order, array('asc', 'desc'))) {
+            $order_by = 'list';
+            $order = 'asc';
+        }
 
-        $alias  = XDB::iterator(
-                'SELECT  alias,type
-                   FROM  x4dat.virtual
-                  WHERE  alias
-                   LIKE  {?} AND type="user"
-               ORDER BY  alias', '%@'.$globals->asso('mail_domain'));
-        $page->assign('alias', $alias);
+        $compare = function ($a, $b) use ($order_by, $order)
+        {
+            switch ($order_by) {
+              case 'desc':
+                $a[$order_by] = replace_accent($a[$order_by]);
+                $b[$order_by] = replace_accent($b[$order_by]);
+              case 'list':
+                $res = strcasecmp($a[$order_by], $b[$order_by]);
+                break;
+              case 'nbsub':
+                $res = $a[$order_by] - $b[$order_by];
+                break;
+              default:
+                $res = 0;
+            }
 
+            if ($order == 'asc') {
+                return $res;
+            }
+            return $res * -1;
+        };
+        usort($listes, $compare);
+        $page->assign('listes', $listes);
+        $page->assign('order_by', $order_by);
+        $page->assign('order', $order);
+        $page->assign('aliases', iterate_list_alias($this->get_lists_domain()));
         $page->assign('may_update', may_update());
-    }
+        if (S::suid()) {
+            $page->trigWarning("Attention&nbsp;: l'affichage des listes de diffusion ne tient pas compte de l'option « Voir le site comme&hellip; ».");
+        }
 
-    function handler_create(&$page)
-    {
         global $globals;
+        if (count($listes) > 0 && !$globals->asso('has_ml')) {
+            XDB::execute("UPDATE  groups
+                             SET  flags = CONCAT_WS(',', IF(flags = '', NULL, flags), 'has_ml')
+                           WHERE  id = {?}",
+                         $globals->asso('id'));
+        }
+    }
 
-        if (!$globals->asso('mail_domain')) {
+    function handler_create($page)
+    {
+        if (!$this->get_lists_domain()) {
             return PL_NOT_FOUND;
         }
-        $this->prepare_client($page);
         $page->changeTpl('xnetlists/create.tpl');
 
         if (!Post::has('submit')) {
@@ -135,83 +152,77 @@ class XnetListsModule extends ListsModule
             S::assert_xsrf_token();
         }
 
-        if (!Post::has('liste')) {
-            $page->trigError('champs «adresse souhaitée» vide');
+        if (!Post::has('liste') || !Post::t('liste')) {
+            $page->trigError('Le champs «&nbsp;adresse souhaitée&nbsp;» est vide.');
             return;
         }
 
-        $liste = strtolower(Post::v('liste'));
-
-        if (!preg_match("/^[a-zA-Z0-9\-]*$/", $liste)) {
+        $list = strtolower(Post::t('liste'));
+        if (!preg_match("/^[a-zA-Z0-9\-]*$/", $list)) {
             $page->trigError('le nom de la liste ne doit contenir que des lettres non accentuées, chiffres et tirets');
             return;
         }
 
-        $new = $liste.'@'.$globals->asso('mail_domain');
-        $res = XDB::query('SELECT alias FROM x4dat.virtual WHERE alias={?}', $new);
-
-        if ($res->numRows()) {
-            $page->trigError('cet alias est déjà pris');
+        require_once 'emails.inc.php';
+        if (list_exist($list, $this->get_lists_domain())) {
+            $page->trigError('Cet alias est déjà pris.');
             return;
         }
-        if (!Post::v('desc')) {
-            $page->trigError('le sujet est vide');
+        if (!Post::t('desc')) {
+            $page->trigError('Le sujet est vide.');
             return;
         }
 
-        $ret = $this->client->create_list(
-                    $liste, utf8_decode(Post::v('desc')), Post::v('advertise'),
-                    Post::v('modlevel'), Post::v('inslevel'),
-                    array(S::user()->forlifeEmail()), array(S::user()->forlifeEmail()));
+        $mlist = $this->prepare_list($list);
+        $success = MailingList::create($mlist->mbox, $mlist->domain, S::user(),
+            Post::t('desc'),
+            Post::t('advertise'), Post::t('modlevel'), Post::t('inslevel'),
+            array(S::user()->forlifeEmail()), array(S::user()->forlifeEmail()));
 
-        $dom = strtolower($globals->asso("mail_domain"));
-        $red = $dom.'_'.$liste;
-
-        if (!$ret) {
+        if (!$success) {
             $page->kill("Un problème est survenu, contacter "
                         ."<a href='mailto:support@m4x.org'>support@m4x.org</a>");
             return;
         }
-        foreach (array('', 'owner', 'admin', 'bounces', 'unsubscribe') as $app) {
-            $mdir = $app == '' ? '+post' : '+' . $app;
-            if (!empty($app)) {
-                $app  = '-' . $app;
-            }
-            XDB::execute('INSERT INTO x4dat.virtual (alias,type)
-                                    VALUES({?},{?})', $liste. $app . '@'.$dom, 'list');
-            XDB::execute('INSERT INTO x4dat.virtual_redirect (vid,redirect)
-                                    VALUES ({?}, {?})', XDB::insertId(),
-                                   $red . $mdir . '@listes.polytechnique.org');
-        }
-        pl_redirect('lists/admin/'.$liste);
-    }
+        create_list($mlist->mbox, $mlist->domain);
 
-    function handler_sync(&$page, $liste = null)
-    {
         global $globals;
+        XDB::execute("UPDATE  groups
+                         SET  flags = CONCAT_WS(',', IF(flags = '', NULL, flags), 'has_ml')
+                       WHERE  id = {?}",
+                     $globals->asso('id'));
 
-        if (!$globals->asso('mail_domain')) {
+        pl_redirect('lists/admin/' . $list);
+    }
+
+    function handler_sync($page, $liste = null)
+    {
+        if (!$this->get_lists_domain()) {
             return PL_NOT_FOUND;
         }
-        $this->prepare_client($page);
+        if (!$liste) {
+            return PL_NOT_FOUND;
+        }
+
         $page->changeTpl('xnetlists/sync.tpl');
 
+        $mlist = $this->prepare_list($liste);
+
         if (Env::has('add')) {
             S::assert_xsrf_token();
-            $this->client->mass_subscribe($liste, array_keys(Env::v('add')));
+            $mlist->subscribeBulk(array_keys(Env::v('add')));
         }
 
-        list(,$members) = $this->client->get_members($liste);
+        list(,$members) = $mlist->getMembers();
         $mails = array_map(create_function('$arr', 'return $arr[1];'), $members);
         $subscribers = array_unique($mails);
 
-        $not_in_group_x = array();
-        $not_in_group_ext = array();
-
+        global $globals;
         $ann = XDB::fetchColumn('SELECT  uid
-                                   FROM  groupex.membres
+                                   FROM  group_members
                                   WHERE  asso_id = {?}', $globals->asso('id'));
-        $users = User::getBuildUsersWithUIDs($ann, 'promo,full_name');
+        $users = User::getBulkUsersWithUIDs($ann);
+
         $not_in_list = array();
         foreach ($users as $user) {
             if (!in_array(strtolower($user->forlifeEmail()), $subscribers)) {
@@ -222,69 +233,47 @@ class XnetListsModule extends ListsModule
         $page->assign('not_in_list', $not_in_list);
     }
 
-    function handler_aadmin(&$page, $lfull = null)
+    function handler_aadmin($page, $lfull = null)
     {
-        global $globals;
-
-        if (!$globals->asso('mail_domain') || is_null($lfull)) {
+        if (!$this->get_lists_domain() || is_null($lfull)) {
             return PL_NOT_FOUND;
         }
         $page->changeTpl('xnetlists/alias-admin.tpl');
 
+        require_once 'emails.inc.php';
+        list($local_part, $domain) = explode('@', $lfull);
+        if ($this->get_lists_domain() != $domain || !preg_match("/^[a-zA-Z0-9\-\.]*$/", $local_part)) {
+            global $globals;
+            $page->trigErrorRedirect('Le nom de l\'alias est erroné.', $globals->asso('diminutif') . '/lists');
+        }
+
+
         if (Env::has('add_member')) {
             S::assert_xsrf_token();
 
-            $add = Env::t('add_member');
-            $user = User::getSilent($add);
-            if ($user) {
-                $add = $user->forlifeEmail();
-            } else if (!User::isForeignEmailAddress($add)) {
-                $add = null;
-            }
-            if (!empty($add)) {
-                XDB::execute('INSERT INTO  x4dat.virtual_redirect (vid, redirect)
-                                   SELECT  vid, {?},
-                                     FROM  x4dat.virtual
-                                    WHERE  alias = {?}', strtolower($add), $lfull);
-                $page->trigSuccess($add . ' ajouté.');
+            if (add_to_list_alias(Env::t('add_member'), $local_part, $domain)) {
+                $page->trigSuccess('Ajout réussi.');
             } else {
-                $page->trigError($add . ' n\'existe pas.');
+                $page->trigError('Ajout infructueux.');
             }
         }
 
         if (Env::has('del_member')) {
             S::assert_xsrf_token();
-            XDB::query(
-                    "DELETE FROM  x4dat.virtual_redirect
-                           USING  x4dat.virtual_redirect
-                      INNER JOIN  x4dat.virtual USING(vid)
-                           WHERE  redirect={?} AND alias={?}", Env::v('del_member'), $lfull);
-            pl_redirect('alias/admin/'.$lfull);
-        }
 
-        global $globals;
-        $emails = XDB::fetchColumn('SELECT  redirect
-                                      FROM  virtual_redirect AS vr
-                                INNER JOIN  virtual          AS v  USING(vid)
-                                     WHERE  v.alias = {?}
-                                  ORDER BY  redirect', $lfull);
-        $mem = array();
-        foreach ($emails as $email) {
-            $user = User::getSilent($email);
-            if ($user) {
-                $mem[] = array('user' => $user, 'email' => $email);
+            if (delete_from_list_alias(Env::t('del_member'), $local_part, $domain)) {
+                $page->trigSuccess('Suppression réussie.');
             } else {
-                $mem[] = array('email' => $email);
+                $page->trigError('Suppression infructueuse.');
             }
         }
-        $page->assign('mem', $mem);
+
+        $page->assign('members', list_alias_members($local_part, $domain));
     }
 
-    function handler_acreate(&$page)
+    function handler_acreate($page)
     {
-        global $globals;
-
-        if (!$globals->asso('mail_domain')) {
+        if (!$this->get_lists_domain()) {
             return PL_NOT_FOUND;
         }
         $page->changeTpl('xnetlists/alias-create.tpl');
@@ -296,34 +285,32 @@ class XnetListsModule extends ListsModule
         }
 
         if (!Post::has('liste')) {
-            $page->trigError('champs «adresse souhaitée» vide');
+            $page->trigError('Le champs «&nbsp;adresse souhaitée&nbsp;» est vide.');
             return;
         }
-        $liste = Post::v('liste');
-        if (!preg_match("/^[a-zA-Z0-9\-\.]*$/", $liste)) {
-            $page->trigError('le nom de l\'alias ne doit contenir que des lettres,'
-                            .' chiffres, tirets et points');
+        $list = Post::v('liste');
+        if (!preg_match("/^[a-zA-Z0-9\-\.]*$/", $list)) {
+            $page->trigError('Le nom de l\'alias ne doit contenir que des lettres,'
+                            .' chiffres, tirets et points.');
             return;
         }
 
-        $new = $liste.'@'.$globals->asso('mail_domain');
-        $res = XDB::query('SELECT COUNT(*) FROM x4dat.virtual WHERE alias={?}', $new);
-        $n   = $res->fetchOneCell();
-        if ($n) {
-            $page->trigError('cet alias est déjà pris');
+        require_once 'emails.inc.php';
+        $lists_domain = $this->get_lists_domain();
+        if (list_exist($list, $lists_domain)) {
+            $page->trigError('Cet alias est déjà pris.');
             return;
         }
 
-        XDB::query('INSERT INTO x4dat.virtual (alias,type) VALUES({?}, "user")', $new);
-
-        pl_redirect("alias/admin/$new");
+        add_to_list_alias(S::i('uid'), $list, $lists_domain);
+        pl_redirect('alias/admin/' . $list . '@' . $lists_domain);
     }
 
-    function handler_profile(&$page, $user = null)
+    function handler_profile($page, $user = null)
     {
         http_redirect('https://www.polytechnique.org/profile/'.$user);
     }
 }
 
-// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
+// vim:set et sw=4 sts=4 sws=4 foldmethod=marker fenc=utf-8:
 ?>