Uses user's visibility limitations to display vcards (Closes #1478).
[platal.git] / modules / xnetgrp.php
index 91ec6af..08342a0 100644 (file)
@@ -29,31 +29,32 @@ class XnetGrpModule extends PLModule
             '%grp/asso.php'        => $this->make_hook('index',                 AUTH_PUBLIC),
             '%grp/logo'            => $this->make_hook('logo',                  AUTH_PUBLIC),
             '%grp/site'            => $this->make_hook('site',                  AUTH_PUBLIC),
-            '%grp/edit'            => $this->make_hook('edit',                  AUTH_MDP,    'groupadmin'),
-            '%grp/mail'            => $this->make_hook('mail',                  AUTH_MDP,    'groupadmin'),
-            '%grp/forum'           => $this->make_hook('forum',                 AUTH_MDP,    'groupmember'),
-            '%grp/annuaire'        => $this->make_hook('annuaire',              AUTH_MDP,    'groupannu'),
-            '%grp/annuaire/vcard'  => $this->make_hook('vcard',                 AUTH_MDP,    'groupmember:groupannu'),
-            '%grp/annuaire/csv'    => $this->make_hook('csv',                   AUTH_MDP,    'groupmember:groupannu'),
-            '%grp/trombi'          => $this->make_hook('trombi',                AUTH_MDP,    'groupannu'),
-            '%grp/geoloc'          => $this->make_hook('geoloc',                AUTH_MDP,    'groupannu'),
+            '%grp/edit'            => $this->make_hook('edit',                  AUTH_MDP, 'groupadmin'),
+            '%grp/mail'            => $this->make_hook('mail',                  AUTH_MDP, 'groupadmin'),
+            '%grp/forum'           => $this->make_hook('forum',                 AUTH_MDP, 'groupmember'),
+            '%grp/annuaire'        => $this->make_hook('annuaire',              AUTH_MDP, 'groupannu'),
+            '%grp/annuaire/vcard'  => $this->make_hook('vcard',                 AUTH_MDP, 'groupmember:groupannu'),
+            '%grp/annuaire/csv'    => $this->make_hook('csv',                   AUTH_MDP, 'groupmember:groupannu'),
+            '%grp/directory/sync'  => $this->make_hook('directory_sync',        AUTH_MDP, 'groupadmin'),
+            '%grp/trombi'          => $this->make_hook('trombi',                AUTH_MDP, 'groupannu'),
+            '%grp/geoloc'          => $this->make_hook('geoloc',                AUTH_MDP, 'groupannu'),
             '%grp/subscribe'       => $this->make_hook('subscribe',             AUTH_MDP),
-            '%grp/subscribe/valid' => $this->make_hook('subscribe_valid',       AUTH_MDP,    'groupadmin'),
-            '%grp/unsubscribe'     => $this->make_hook('unsubscribe',           AUTH_MDP,    'groupmember'),
+            '%grp/subscribe/valid' => $this->make_hook('subscribe_valid',       AUTH_MDP, 'groupadmin'),
+            '%grp/unsubscribe'     => $this->make_hook('unsubscribe',           AUTH_MDP, 'groupmember'),
 
             '%grp/change_rights'   => $this->make_hook('change_rights',         AUTH_MDP),
-            '%grp/admin/annuaire'  => $this->make_hook('admin_annuaire',        AUTH_MDP,    'groupadmin'),
-            '%grp/member'          => $this->make_hook('admin_member',          AUTH_MDP,    'groupadmin'),
-            '%grp/member/new'      => $this->make_hook('admin_member_new',      AUTH_MDP,    'groupadmin'),
-            '%grp/member/new/ajax' => $this->make_hook('admin_member_new_ajax', AUTH_MDP,    'user', NO_AUTH),
-            '%grp/member/del'      => $this->make_hook('admin_member_del',      AUTH_MDP,    'groupadmin'),
-            '%grp/member/suggest'  => $this->make_hook('admin_member_suggest',  AUTH_MDP,    'groupadmin'),
+            '%grp/admin/annuaire'  => $this->make_hook('admin_annuaire',        AUTH_MDP, 'groupadmin'),
+            '%grp/member'          => $this->make_hook('admin_member',          AUTH_MDP, 'groupadmin'),
+            '%grp/member/new'      => $this->make_hook('admin_member_new',      AUTH_MDP, 'groupadmin'),
+            '%grp/member/new/ajax' => $this->make_hook('admin_member_new_ajax', AUTH_MDP, 'user', NO_AUTH),
+            '%grp/member/del'      => $this->make_hook('admin_member_del',      AUTH_MDP, 'groupadmin'),
+            '%grp/member/suggest'  => $this->make_hook('admin_member_suggest',  AUTH_MDP, 'groupadmin'),
 
             '%grp/rss'             => $this->make_token_hook('rss',             AUTH_PUBLIC),
-            '%grp/announce/new'    => $this->make_hook('edit_announce',         AUTH_MDP,    'groupadmin'),
-            '%grp/announce/edit'   => $this->make_hook('edit_announce',         AUTH_MDP,    'groupadmin'),
+            '%grp/announce/new'    => $this->make_hook('edit_announce',         AUTH_MDP, 'groupadmin'),
+            '%grp/announce/edit'   => $this->make_hook('edit_announce',         AUTH_MDP, 'groupadmin'),
             '%grp/announce/photo'  => $this->make_hook('photo_announce',        AUTH_PUBLIC),
-            '%grp/admin/announces' => $this->make_hook('admin_announce',        AUTH_MDP,    'groupadmin'),
+            '%grp/admin/announces' => $this->make_hook('admin_announce',        AUTH_MDP, 'groupadmin'),
         );
     }
 
@@ -401,6 +402,113 @@ class XnetGrpModule extends PLModule
         $page->assign('users', $users);
     }
 
+    function handler_directory_sync($page)
+    {
+        global $globals;
+        require_once 'emails.inc.php';
+
+        $page->changeTpl('xnetgrp/sync.tpl');
+        Platal::load('lists', 'lists.inc.php');
+
+        if (Env::has('add_users')) {
+            S::assert_xsrf_token();
+
+            $users = array_keys(Env::v('add_users'));
+            $data = array();
+            foreach ($users as $uid) {
+                $data[] = XDB::format('({?}, {?})', $globals->asso('id'), $uid);
+            }
+            XDB::rawExecute('INSERT INTO  group_members (asso_id, uid)
+                                  VALUES  ' . implode(',', $data));
+        }
+
+        if (Env::has('add_nonusers')) {
+            S::assert_xsrf_token();
+
+            $nonusers = array_keys(Env::v('add_nonusers'));
+            foreach ($nonusers as $email) {
+                if ($user = User::getSilent($email) || !isvalid_email($email)) {
+                    continue;
+                }
+
+                list($local_part, $domain) = explode('@', strtolower($email));
+                $hruid = User::makeHrid($local_part, $domain, 'ext');
+                if ($user = User::getSilent($hruid)) {
+                    continue;
+                }
+
+                $parts = explode('.', $local_part);
+                if (count($parts) == 1) {
+                    $lastname = $display_name = $full_name = $directory_name = ucfirst($local_part);
+                    $firstname = '';
+                } else {
+                    $firstname = ucfirst($parts[0]);
+                    $lastname = ucwords(implode(' ', array_slice($parts, 1)));
+                    $display_name = $firstname;
+                    $full_name = $firstname . ' ' . $lastname;
+                    $directory_name = strtoupper($lastname) . ' ' . $firstname;
+                }
+                XDB::execute('INSERT INTO  accounts (hruid, display_name, full_name, directory_name, firstname, lastname, email, type, state)
+                                   VALUES  ({?}, {?}, {?}, {?}, {?}, {?}, {?}, \'xnet\', \'disabled\')',
+                             $hruid, $display_name, $full_name, $directory_name, $firstname, $lastname, $email);
+                $uid = XDB::insertId();
+                XDB::execute('INSERT INTO  group_members (asso_id, uid)
+                                   VALUES  ({?}, {?})',
+                             $globals->asso('id'), $uid);
+            }
+        }
+
+        if (Env::has('add_users') || Env::has('add_nonusers')) {
+            $page->trigSuccess('Ajouts réalisés avec succès.');
+        }
+
+        $user = S::user();
+        $client = new MMList($user, $globals->asso('mail_domain'));
+        $lists = $client->get_lists();
+        $members = array();
+        foreach ($lists as $list) {
+            $details = $client->get_members($list['list']);
+            $members = array_merge($members, list_extract_members($details[1]));
+        }
+        $members = array_unique($members);
+        $uids = array();
+        $users = array();
+        $nonusers = array();
+        foreach ($members as $email) {
+            if ($user = User::getSilent($email)) {
+                $uids[] = $user->id();
+            } else {
+                $nonusers[] = $email;
+            }
+        }
+
+        $aliases = iterate_list_alias($globals->asso('mail_domain'));
+        foreach ($aliases as $alias) {
+            list($local_part, $domain) = explode('@', $alias);
+            $aliases_members = list_alias_members($local_part, $domain);
+            $users = array_merge($users, $aliases_members['users']);
+            $nonusers = array_merge($nonusers, $aliases_members['nonusers']);
+        }
+        foreach ($users as $user) {
+            $uids[] = $user->id();
+        }
+        $nonusers = array_unique($nonusers);
+        $uids = array_unique($uids);
+        $uids = XDB::fetchColumn('SELECT  a.uid
+                                    FROM  accounts AS a
+                                   WHERE  a.uid IN {?} AND NOT EXISTS (SELECT  *
+                                                                         FROM  group_members AS g
+                                                                        WHERE  a.uid = g.uid AND g.asso_id = {?})',
+                                 $uids, $globals->asso('id'));
+
+        $users = User::getBulkUsersWithUIDs($uids);
+        usort($users, 'User::compareDirectoryName');
+        sort($nonusers);
+
+        $page->assign('users', $users);
+        $page->assign('nonusers', $nonusers);
+    }
+
     private function removeSubscriptionRequest($uid)
     {
         global $globals;
@@ -659,20 +767,25 @@ class XnetGrpModule extends PLModule
         S::assert_xsrf_token();
         $suggest_account_activation = false;
 
+        // FS#703 : $_GET is urldecoded twice, hence
+        // + (the data) => %2B (in the url) => + (first decoding) => ' ' (second decoding)
+        // Since there can be no spaces in emails, we can fix this with :
+        $email = str_replace(' ', '+', $email);
+
         // Finds or creates account: first cases are for users with an account.
         if (!User::isForeignEmailAddress($email)) {
             // Standard account
-            $user = User::get($email);
+            $user = User::getSilent($email);
         } else if (!isvalid_email($email)) {
             // email might not be a regular email but an alias or a hruid
-            $user = User::get($email);
+            $user = User::getSilent($email);
             if (!$user) {
                 // need a valid email address
                 $page->trigError('«&nbsp;<strong>' . $email . '</strong>&nbsp;» n\'est pas une adresse email valide.');
                 return;
             }
         } else if (Env::v('x') && Env::i('userid')) {
-            $user = User::getWithUID(Env::i('userid'));
+            $user = User::getSilentWithUID(Env::i('userid'));
             if (!$user) {
                 $page->trigError('Utilisateur invalide.');
                 return;
@@ -708,13 +821,14 @@ class XnetGrpModule extends PLModule
             list($mbox, $domain) = explode('@', strtolower($email));
             $hruid = User::makeHrid($mbox, $domain, 'ext');
             // User might already have an account (in another group for example).
-            $user = User::get($hruid);
+            $user = User::getSilent($hruid);
 
             // If the user has no account yet, creates new account: build names from email address.
             if (empty($user)) {
                 $parts = explode('.', $mbox);
                 if (count($parts) == 1) {
-                    $display_name = $full_name = $directory_name = ucfirst($mbox);
+                    $lastname = $display_name = $full_name = $directory_name = ucfirst($mbox);
+                    $firstname = '';
                 } else {
                     $firstname = ucfirst($parts[0]);
                     $lastname = ucwords(implode(' ', array_slice($parts, 1)));
@@ -722,27 +836,13 @@ class XnetGrpModule extends PLModule
                     $full_name = "$firstname $lastname";
                     $directory_name = strtoupper($lastname) . " " . $firstname;
                 }
-                XDB::execute('INSERT INTO  accounts (hruid, display_name, full_name, directory_name,
-                                           email, type)
-                                   VALUES  ({?}, {?}, {?}, {?}, {?}, \'xnet\')',
-                             $hruid, $display_name, $full_name, $directory_name, $email);
-                $user = User::get($hruid);
+                XDB::execute('INSERT INTO  accounts (hruid, display_name, full_name, directory_name, firstname, lastname, email, type, state)
+                                   VALUES  ({?}, {?}, {?}, {?}, {?}, {?}, {?}, \'xnet\', \'disabled\')',
+                             $hruid, $display_name, $full_name, $directory_name, $firstname, $lastname, $email);
+                $user = User::getSilent($hruid);
             }
 
-            // Check if the user is has a pending or active account.
-            $active = XDB::fetchOneCell('SELECT  state = \'active\'
-                                           FROM  accounts
-                                          WHERE  uid = {?}',
-                                        $user->id());
-            $pending = XDB::fetchOneCell('SELECT  uid
-                                            FROM  register_pending_xnet
-                                           WHERE  uid = {?}',
-                                         $user->id());
-            $requested = AccountReq::isPending($user->id());
-
-            if (!($active || $pending || $requested)) {
-                $suggest_account_activation = true;
-            }
+            $suggest_account_activation = $this->suggest($user);
         }
 
         if ($user) {
@@ -758,10 +858,34 @@ class XnetGrpModule extends PLModule
         }
     }
 
+    // Check if the user has a pending or active account, and thus if we should her account's activation.
+    private function suggest(PlUser $user)
+    {
+        $active = XDB::fetchOneCell('SELECT  state = \'active\'
+                                       FROM  accounts
+                                      WHERE  uid = {?}',
+                                    $user->id());
+        $pending = XDB::fetchOneCell('SELECT  uid
+                                        FROM  register_pending_xnet
+                                       WHERE  uid = {?}',
+                                     $user->id());
+        $requested = AccountReq::isPending($user->id());
+
+        if ($active || $pending || $requested) {
+            return false;
+        }
+        return true;
+    }
+
     function handler_admin_member_suggest($page, $hruid, $email)
     {
         $page->changeTpl('xnetgrp/membres-suggest.tpl');
 
+        // FS#703 : $_GET is urldecoded twice, hence
+        // + (the data) => %2B (in the url) => + (first decoding) => ' ' (second decoding)
+        // Since there can be no spaces in emails, we can fix this with :
+        $email = str_replace(' ', '+', $email);
+
         if (Post::has('suggest')) {
             if (Post::t('suggest') == 'yes') {
                 $user = S::user();
@@ -888,11 +1012,10 @@ class XnetGrpModule extends PLModule
         } else {
             $page->trigWarning('Tu as été désinscrit du groupe, mais des erreurs se sont produites lors des désinscriptions des alias et des listes de diffusion.');
         }
-        if ($user->type == 'xnet' && $hasSingleGroup && Post::has('accountDeletion')) {
-            XDB::execute('DELETE FROM  acounts
-                                WHERE  uid = {?}',
-                         $user->id());
-            $page->trigSuccess('Ton compte a bien été supprimé.');
+
+        // If user is of type xnet account and this was her last group, disable the account.
+        if ($user->type == 'xnet' && $hasSingleGroup) {
+            $user->clear(true);
         }
         $page->assign('is_member', is_member(true));
     }
@@ -928,28 +1051,13 @@ class XnetGrpModule extends PLModule
             $page->trigWarning("{$user->fullName()} a été désinscrit du groupe, mais des erreurs subsistent&nbsp;!");
         }
 
-        // Either deletes or notifies site administrators if it was the last group
-        // of a xnet account.
+        // If user is of type xnet account and this was her last group, disable the account.
         if ($user->type == 'xnet' && $hasSingleGroup) {
-            if ($user->state == 'pending') {
-                // If the user has never logged in the site, we delete her account.
-                XDB::execute('DELETE FROM  acounts
-                                    WHERE  uid = {?}',
-                             $user->id());
-            } else {
-                // It the user has already logged in the site, we notify site
-                // administrators that there is a new xnet account without any
-                // group.
-                $mailer = new PlMailer('xnetgrp/unsubscription.mail.tpl');
-                $mailer->assign('user', $user);
-                $mailer->assign('groupId', $globals->asso('id'));
-                $mailer->assign('groupName', $globals->asso('nom'));
-                $mailer->send();
-            }
+            $user->clear(true);
         }
     }
 
-    private function changeLogin(PlPage &$page, PlUser &$user, $login)
+    private function changeLogin(PlPage $page, PlUser $user, $login)
     {
         // Search the user's uid.
         $xuser = User::getSilent($login);
@@ -993,6 +1101,7 @@ class XnetGrpModule extends PLModule
         $mmlist = new MMList(S::user(), $globals->asso('mail_domain'));
 
         if (Post::has('change')) {
+            require_once 'emails.inc.php';
             S::assert_xsrf_token();
 
             // Convert user status to X
@@ -1006,31 +1115,45 @@ class XnetGrpModule extends PLModule
             // Update user info
             $email_changed = (!$user->profile() && strtolower($user->forlifeEmail()) != strtolower(Post::v('email')));
             $from_email = $user->forlifeEmail();
-            if ($user->type == 'virtual' || $user->type == 'xnet') {
+            if ($user->type == 'virtual' || ($user->type == 'xnet' && !$user->perms)) {
+                $lastname = Post::s('lastname');
+                if (Post::s('type') != 'virtual') {
+                    $firstname = Post::s('firstname');
+                    $full_name = $firstname . ' ' . $lastname;
+                    $directory_name = mb_strtoupper($lastname) . ' ' . $firstname;
+                } else {
+                    $firstname = '';
+                    $full_name = $lastname;
+                    $directory_name = mb_strtoupper($lastname);
+                }
                 XDB::query('UPDATE  accounts
                                SET  full_name = {?}, directory_name = {?}, display_name = {?},
-                                    sex = {?}, email = {?}, type = {?}
+                                    firstname = {?}, lastname = {?}, sex = {?}, email = {?}, type = {?}
                              WHERE  uid = {?}',
-                           Post::t('full_name'), Post::t('directory_name'), Post::t('display_name'),
+                           $full_name, $directory_name, Post::t('display_name'), $firstname, $lastname,
                            (Post::t('sex') == 'male') ? 'male' : 'female', Post::t('email'),
                            (Post::t('type') == 'xnet') ? 'xnet' : 'virtual', $user->id());
-                // If user is of type xnet and new password is given.
-                if (!Post::blank('pwhash') && Post::t('type') == 'xnet') {
-                    XDB::query('UPDATE  accounts
-                                   SET  password = {?}
-                                 WHERE  uid = {?}',
-                               Post::t('pwhash'), $user->id());
-                }
             } else if (!$user->perms) {
                 XDB::query('UPDATE  accounts
                                SET  email = {?}
                              WHERE  uid = {?}',
                            Post::t('email'), $user->id());
             }
+            if (require_email_update($user, Post::t('email'))) {
+                $listClient = new MMList(S::user());
+                $listClient->change_user_email($user->forlifeEmail(), Post::t('email'));
+                update_alias_user($user->forlifeEmail(), Post::t('email'));
+            }
             if (XDB::affectedRows()) {
                 $page->trigSuccess('Données de l\'utilisateur mises à jour.');
             }
 
+            if (($user->type == 'xnet' && !$user->perms) && Post::b('suggest')) {
+                $request = new AccountReq(S::user(), $user->hruid, Post::t('email'), $globals->asso('nom'));
+                $request->submit();
+                $page->trigSuccess('Le compte va bientôt être activé.');
+            }
+
             // Update group params for user
             $perms = Post::v('group_perms');
             $comm  = Post::t('comm');
@@ -1088,16 +1211,17 @@ class XnetGrpModule extends PLModule
             foreach (Env::v('ml3', array()) as $ml => $state) {
                 require_once 'emails.inc.php';
                 $ask = !empty($_REQUEST['ml4'][$ml]);
+                list($local_part, ) = explode('@', $ml);
                 if($state == $ask) {
                     if ($state && $email_changed) {
-                        update_list_alias($user, $from_email, $ml, $globals->asso('mail_domain'));
+                        update_list_alias($user->id(), $from_email, $local_part, $globals->asso('mail_domain'));
                         $page->trigSuccess("L'abonnement de {$user->fullName()} à $ml a été mis à jour.");
                     }
                 } else if($ask) {
-                    add_to_list_alias($user, $ml, $globals->asso('mail_domain'));
+                    add_to_list_alias($user->id(), $local_part, $globals->asso('mail_domain'));
                     $page->trigSuccess("{$user->fullName()} a été abonné à $ml.");
                 } else {
-                    delete_from_list_alias($user, $ml, $globals->asso('mail_domain'));
+                    delete_from_list_alias($user->id(), $local_part, $globals->asso('mail_domain'));
                     $page->trigSuccess("{$user->fullName()} a été désabonné de $ml.");
                 }
             }
@@ -1106,9 +1230,8 @@ class XnetGrpModule extends PLModule
         $res = XDB::rawFetchAllAssoc('SHOW COLUMNS FROM group_members LIKE \'position\'');
         $positions = str_replace(array('enum(', ')', '\''), '', $res[0]['Type']);
 
-        $page->addJsLink('password.js');
-        $page->assign('onlyGroup', ($user->groupCount() == 1));
         $page->assign('user', $user);
+        $page->assign('suggest', $this->suggest($user));
         $page->assign('listes', $mmlist->get_lists($user->forlifeEmail()));
         $page->assign('alias', $user->emailGroupAliases($globals->asso('mail_domain')));
         $page->assign('positions', explode(',', $positions));
@@ -1248,13 +1371,13 @@ class XnetGrpModule extends PLModule
                 if (!empty($art['contact_html'])) {
                     $fulltext .= "\n\n'''Contacts :'''\\\\\n" . $art['contact_html'];
                 }
-                $post = null;/*
+                $post = null;
                 if ($globals->asso('forum')) {
                     require_once 'banana/forum.inc.php';
                     $banana = new ForumsBanana(S::user());
                     $post = $banana->post($globals->asso('forum'), null,
                                           $art['titre'], MiniWiki::wikiToText($fulltext, false, 0, 80));
-                }*/
+                }
                 XDB::query('INSERT INTO  group_announces (uid, asso_id, create_date, titre, texte, contacts,
                                                           expiration, promo_min, promo_max, flags, post_id)
                                  VALUES  ({?}, {?}, NOW(), {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?})',