Delete profile_addresses_components rows where deleting profile_addresses ones
[platal.git] / modules / xnetevents.php
index 10d7259..76abf6c 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   *
@@ -26,20 +26,22 @@ class XnetEventsModule extends PLModule
     function handlers()
     {
         return array(
-            '%grp/events'       => $this->make_hook('events',  AUTH_MDP),
-            '%grp/events/sub'   => $this->make_hook('sub',     AUTH_MDP),
-            '%grp/events/csv'   => $this->make_hook('csv',     AUTH_MDP, 'user', NO_HTTPS),
-            '%grp/events/ical'  => $this->make_hook('ical',    AUTH_MDP, 'user', NO_HTTPS),
-            '%grp/events/edit'  => $this->make_hook('edit',    AUTH_MDP, 'groupadmin'),
-            '%grp/events/admin' => $this->make_hook('admin',   AUTH_MDP, 'groupmember'),
+            '%grp/events'       => $this->make_hook('events', AUTH_PASSWD, 'groups'),
+            '%grp/events/sub'   => $this->make_hook('sub',    AUTH_PASSWD, 'groups'),
+            '%grp/events/csv'   => $this->make_hook('csv',    AUTH_PASSWD, 'groups', NO_HTTPS),
+            '%grp/events/ical'  => $this->make_hook('ical',   AUTH_PASSWD, 'groups', NO_HTTPS),
+            '%grp/events/edit'  => $this->make_hook('edit',   AUTH_PASSWD, 'groupadmin'),
+            '%grp/events/admin' => $this->make_hook('admin',  AUTH_PASSWD, 'groupmember'),
         );
     }
 
-    function handler_events(&$page, $archive = null)
+    function handler_events($page, $archive = null)
     {
         global $globals;
 
         $page->changeTpl('xnetevents/index.tpl');
+        $this->load('xnetevents.inc.php');
+
         $action = null;
         $archive = ($archive == 'archive' && may_update());
 
@@ -60,7 +62,7 @@ class XnetEventsModule extends PLModule
             }
             S::assert_xsrf_token();
 
-            $res = XDB::query("SELECT asso_id, short_name FROM groupex.evenements
+            $res = XDB::query("SELECT asso_id, short_name FROM group_events
                                 WHERE eid = {?} AND asso_id = {?}",
                               $eid, $globals->asso('id'));
 
@@ -73,198 +75,254 @@ class XnetEventsModule extends PLModule
         if ($action == 'del') {
             // deletes the event mailing aliases
             if ($tmp[1]) {
-                XDB::execute(
-                    "DELETE FROM virtual WHERE type = 'evt' AND alias LIKE {?}",
-                    $tmp[1].'-absents@%');
-                XDB::execute(
-                    "DELETE FROM virtual WHERE type = 'evt' AND alias LIKE {?}",
-                    $tmp[1].'-participants@%');
+                require_once 'emails.inc.php';
+                foreach (explode(',', $globals->xnet->event_lists) as $suffix) {
+                    delete_list_alias($tmp[1] . $suffix, $globals->xnet->evts_domain, 'event');
+                }
             }
 
+            // archive le paiement associé si il existe
+            $pay_id = XDB::fetchOneCell("SELECT paiement_id
+                                           FROM group_events
+                                          WHERE eid = {?} AND asso_id = {?}",
+                                        $eid, $globals->asso('id')); 
+            if (!$pay_id=='') {
+                XDB::execute("UPDATE payments
+                                 SET flags = 'old'
+                               WHERE id = {?}",
+                             $pay_id);
+            }
             // deletes the event items
-            XDB::execute("DELETE FROM groupex.evenements_items WHERE eid = {?}", $eid);
+            XDB::execute('DELETE FROM  group_event_items
+                                WHERE  eid = {?}', $eid);
 
             // deletes the event participants
-            XDB::execute("DELETE FROM groupex.evenements_participants
-                                    WHERE eid = {?}", $eid);
+            XDB::execute('DELETE FROM  group_event_participants
+                                WHERE  eid = {?}', $eid);
 
             // deletes the event
-            XDB::execute("DELETE FROM groupex.evenements
-                                    WHERE eid = {?} AND asso_id = {?}",
-                                   $eid, $globals->asso('id'));
+            XDB::execute('DELETE FROM  group_events
+                                WHERE  eid = {?} AND asso_id = {?}',
+                         $eid, $globals->asso('id'));
 
             // delete the requests for payments
-            require_once 'validations.inc.php';
-            XDB::execute("DELETE FROM requests
-                                    WHERE type = 'paiements' AND data LIKE {?}",
-                                   PayReq::same_event($eid, $globals->asso('id')));
+            XDB::execute("DELETE FROM  requests
+                                WHERE  type = 'paiements' AND data LIKE {?}",
+                         PayReq::same_event($eid, $globals->asso('id')));
             $globals->updateNbValid();
         }
 
         if ($action == 'archive') {
-            XDB::execute("UPDATE groupex.evenements
+            $pay_id = XDB::fetchOneCell("SELECT paiement_id 
+                                           FROM group_events
+                                          WHERE eid = {?} AND asso_id = {?}",
+                                        $eid, $globals->asso('id'));
+            if (!$pay_id=='') {
+                XDB::execute("UPDATE payments
+                                 SET flags = 'old'
+                               WHERE id = {?}",
+                               $pay_id);
+            }
+            XDB::execute("UPDATE group_events
                              SET archive = 1
                            WHERE eid = {?} AND asso_id = {?}",
-                         $eid, $globals->asso('id'));
+                           $eid, $globals->asso('id'));
         }
 
         if ($action == 'unarchive') {
-            XDB::execute("UPDATE groupex.evenements
+            $pay_id = XDB::fetchOneCell("SELECT paiement_id FROM group_events
+                                     WHERE eid = {?} AND asso_id = {?}",
+                                   $eid, $globals->asso('id'));
+            if (!$pay_id=='') {
+                XDB::execute("UPDATE payments
+                                 SET flags = ''
+                               WHERE id = {?}",
+                               $pay_id);
+            }
+            XDB::execute("UPDATE group_events
                              SET archive = 0
                            WHERE eid = {?} AND asso_id = {?}",
                          $eid, $globals->asso('id'));
         }
 
         $page->assign('archive', $archive);
-        $evenements = XDB::iterator(
-                "SELECT  e.*, LEFT(10, e.debut) AS debut_day, LEFT(10, e.fin) AS fin_day,
-                         IF(e.deadline_inscription, e.deadline_inscription >= LEFT(NOW(), 10),
-                            1) AS inscr_open, e.deadline_inscription,
-                         u.nom, u.prenom, u.promo, a.alias,
-                         MAX(ep.nb) IS NOT NULL AS inscrit, MAX(ep.paid) AS paid
-                  FROM  groupex.evenements  AS e
-            INNER JOIN  x4dat.auth_user_md5 AS u ON u.user_id = e.organisateur_uid
-            INNER JOIN  x4dat.aliases       AS a ON (a.type = 'a_vie' AND a.id = u.user_id)
-             LEFT JOIN  groupex.evenements_participants AS ep ON (ep.eid = e.eid AND ep.uid = {?})
-                 WHERE  asso_id = {?}
-                   AND  archive = " . ($archive ? "1 " : "0 ")
-              . "GROUP BY  e.eid
-                 ORDER BY  inscr_open DESC, debut DESC", S::v('uid'), $globals->asso('id'));
-
-        $evts = array();
-        $undisplayed_events = 0;
 
-        while ($e = $evenements->next()) {
+        if (Post::has('order')) {
+            $order = Post::v('order');
+            XDB::execute("UPDATE groups
+                             SET event_order = {?}
+                           WHERE id = {?}",
+                          $order, $globals->asso('id'));
+        }
+        $order = get_event_order($globals->asso('id'));
+        $evts = get_events($globals->asso('id'), $order, $archive);
+        $page->assign('order', $order);
+
+        $undisplayed_events = 0;
+        foreach ($evts as $eid => &$e) {
             if (!is_member() && !may_update() && !$e['accept_nonmembre']) {
                 $undisplayed_events ++;
                 continue;
             }
 
             $e['show_participants'] = ($e['show_participants'] && (is_member() || may_update()));
-            $res = XDB::query(
-                "SELECT titre, details, montant, ei.item_id, nb, ep.paid
-                   FROM groupex.evenements_items AS ei
-              LEFT JOIN groupex.evenements_participants AS ep
-                        ON (ep.eid = ei.eid AND ep.item_id = ei.item_id AND uid = {?})
-                  WHERE ei.eid = {?}",
-                    S::v('uid'), $e['eid']);
-            $e['moments'] = $res->fetchAllAssoc();
-
+            $e['items'] = get_event_items($eid);
             $e['topay'] = 0;
-            $e['paid']  = $e['moments'][0]['paid'];
-            foreach ($e['moments'] as $m) {
-                $e['topay'] += $m['nb'] * $m['montant'];
+            $e['paid']  = 0;
+            $sub = get_event_subscription($eid, S::i('uid'));
+            if (empty($sub)) {
+                $e['inscrit'] = false;
+            } else {
+                $e['inscrit'] = true;
+                foreach ($e['items'] as $item_id => $m) {
+                    if (isset($sub[$item_id])) {
+                        $e['topay'] += $sub[$item_id]['nb'] * $m['montant'];
+                        $e['paid'] += $sub[$item_id]['paid'];
+                    }
+                }
             }
+            $e['sub'] = $sub;
 
-            $query = XDB::query(
-                "SELECT montant
-                   FROM {$globals->money->mpay_tprefix}transactions AS t
-                 WHERE ref = {?} AND uid = {?}", $e['paiement_id'], S::v('uid'));
-            $montants = $query->fetchColumn();
+            $telepaid = get_event_telepaid($eid, S::i('uid'));
+            $e['paid'] += $telepaid;
 
-            foreach ($montants as $m) {
-                $p = strtr(substr($m, 0, strpos($m, 'EUR')), ',', '.');
-                $e['paid'] += trim($p);
+            $e['date'] = make_event_date($e['debut'], $e['fin']);
+            if ($e['deadline_inscription'] == null || strtotime($e['deadline_inscription']) >= time()) {
+                $e['inscr_open'] = true;
+            } else {
+                $e['inscr_open'] = false;
             }
 
             if (Env::has('updated') && $e['eid'] == Env::i('updated')) {
                 $page->assign('updated', $e);
             }
-            $evts[] = $e;
         }
 
         $page->assign('evenements', $evts);
         $page->assign('undisplayed_events', $undisplayed_events);
     }
 
-    function handler_sub(&$page, $eid = null)
+    function handler_sub($page, $eid = null)
     {
         $this->load('xnetevents.inc.php');
         $page->changeTpl('xnetevents/subscribe.tpl');
 
-        $evt = get_event_detail($eid);
-        if (!$evt) {
+        $evt = get_event($eid);
+        if (is_null($evt)) {
             return PL_NOT_FOUND;
         }
 
+        global $globals;
+
         if (!$evt['inscr_open']) {
             $page->kill('Les inscriptions pour cet événement sont closes');
         }
         if (!$evt['accept_nonmembre'] && !is_member() && !may_update()) {
-            $page->kill('Cet événement est fermé aux non-membres du groupe');
+            $url = $globals->asso('sub_url');
+            if (empty($url)) {
+                $url = $platal->ns . 'subscribe';
+            }
+            $page->kill('Cet événement est reservé aux membres du groupe ' . $globals->asso('nom') .
+                        '. Pour devenir membre, rends-toi sur la page de <a href="' . $url . '">demande d\'inscripton</a>.');
         }
 
-        global $globals;
-        $res = XDB::query("SELECT  stamp FROM requests
+        $res = XDB::query("SELECT  stamp
+                             FROM  requests
                             WHERE  type = 'paiements' AND data LIKE {?}",
-                           PayReq::same_event($evt['eid'], $globals->asso('id')));
+                           PayReq::same_event($eid, $globals->asso('id')));
         $page->assign('validation', $res->numRows());
-        $page->assign('event', $evt);
 
-        if (!Post::has('submit')) {
-            return;
-        } else {
-            S::assert_xsrf_token();
-        }
-
-        $moments = Post::v('moment',    array());
-        $pers    = Post::v('personnes', array());
-        $subs    = array();
+        $page->assign('eid', $eid);
+        $page->assign('event', $evt);
 
-        foreach ($moments as $j => $v) {
-            $subs[$j] = intval($v);
+        $items = get_event_items($eid);
+        $subs = get_event_subscription($eid, S::v('uid'));
 
-            // retreive ohter field when more than one person
-            if ($subs[$j] == 2) {
-                if (!isset($pers[$j]) || !is_numeric($pers[$j])
-                ||  $pers[$j] < 0)
-                {
-                    $page->trigError('Tu dois choisir un nombre d\'invités correct !');
-                    return;
+        if (Post::has('submit')) {
+            S::assert_xsrf_token();
+            $moments = Post::v('moment',    array());
+            $pers    = Post::v('personnes', array());
+            $old_subs = $subs;
+            $subs    = array();
+
+            foreach ($moments as $j => $v) {
+                $subs[$j] = intval($v);
+
+                // retrieve other field when more than one person
+                if ($subs[$j] == 2) {
+                    if (!isset($pers[$j]) || !is_numeric($pers[$j]) || $pers[$j] < 0) {
+                        $page->trigError("Tu dois choisir un nombre d'invités correct&nbsp;!");
+                        return;
+                    }
+                    $subs[$j] = $pers[$j];
                 }
-                $subs[$j] = 1 + $pers[$j];
             }
-        }
 
-        // impossible to unsubscribe if you already paid sthing
-        if (!array_sum($subs) && $evt['paid'] != 0) {
-            $page->trigError("Impossible de te désinscrire complètement ".
-                            "parce que tu as fait un paiement par ".
-                            "chèque ou par liquide. Contacte un ".
-                            "administrateur du groupe si tu es sûr de ".
-                            "ne pas venir");
-            return;
-        }
-
-        // update actual inscriptions
-        $updated = false;
-        $total   = 0;
-        $paid    = $evt['paid'] ? $evt['paid'] : 0;
-        $telepaid= $evt['telepaid'] ? $evt['telepaid'] : 0;
-        foreach ($subs as $j => $nb) {
-            if ($nb >= 0) {
-                XDB::execute(
-                    "REPLACE INTO  groupex.evenements_participants
-                           VALUES  ({?}, {?}, {?}, {?}, {?}, {?})",
-                    $eid, S::v('uid'), $j, $nb, Env::has('notify_payment') ? 'notify_payment' : '',
-                    $j == 1 ? $paid - $telepaid : 0);
-                $updated = $eid;
+            // count what the user must pay, and what he manually paid
+            $manual_paid = 0;
+            foreach ($items as $item_id => $item) {
+                if (array_key_exists($item_id, $old_subs)) {
+                    $manual_paid += $old_subs[$item_id]['paid'];
+                }
+            }
+            // impossible to unsubscribe if you already paid sthing
+            if (!array_sum($subs) && $manual_paid != 0) {
+                $page->trigError("Impossible de te désinscrire complètement " .
+                                "parce que tu as fait un paiement par " .
+                                "chèque ou par liquide. Contacte un " .
+                                "administrateur du groupe si tu es sûr de " .
+                                "ne pas venir.");
+                $updated = false;
             } else {
-                XDB::execute(
-                    "DELETE FROM  groupex.evenements_participants
-                           WHERE  eid = {?} AND uid = {?} AND item_id = {?}",
-                    $eid, S::v("uid"), $j);
-                $updated = $eid;
+                // update actual inscriptions
+                $updated = subscribe(S::v('uid'), $eid, $subs);
+            }
+            if ($updated) {
+                $evt = get_event_detail($eid);
+                if ($evt['topay'] > 0) {
+                    $page->trigSuccess('Ton inscription à l\'événement a été mise à jour avec succès, tu peux payer ta participation en cliquant ci-dessous');
+                } else {
+                    $page->trigSuccess('Ton inscription à l\'événement a été mise à jour avec succès.');
+                }
+
+                if ($evt['subscription_notification'] != 'nobody') {
+                    $mailer = new PlMailer('xnetevents/subscription-notif.mail.tpl');
+                    if ($evt['subscription_notification'] != 'creator') {
+                        $admins = $globals->asso()->iterAdmins();
+                        while ($admin = $admins->next()) {
+                            $mailer->addTo($admin);
+                        }
+                    }
+                    if ($evt['subscription_notification'] != 'animator') {
+                        $mailer->addTo($evt['organizer']);
+                    }
+                    $mailer->assign('group', $globals->asso('nom'));
+                    $mailer->assign('event', $evt['intitule']);
+                    $mailer->assign('subs', $subs);
+                    $mailer->assign('moments', $evt['moments']);
+                    $mailer->assign('name', S::user()->fullName('promo'));
+                    $mailer->send();
+                }
             }
-            $total += $nb;
         }
-        if ($updated !== false) {
-            subscribe_lists_event($total, S::i('uid'), $evt);
+        $subs = get_event_subscription($eid, S::v('uid'));
+        // count what the user must pay
+        $topay = 0;
+        $manually_paid = 0;
+        foreach ($items as $item_id => $item) {
+            if (array_key_exists($item_id, $subs)) {
+                $topay += $item['montant']*$subs[$item_id]['nb'];
+                $manually_paid += $subs[$item_id]['paid'];
+            }
         }
-        $page->assign('event', get_event_detail($eid));
+        $paid = $manually_paid + get_event_telepaid($eid, S::v('uid'));
+        $page->assign('moments', $items);
+        $page->assign('subs', $subs);
+        $page->assign('topay', $topay);
+        $page->assign('paid', $paid);
     }
 
-    function handler_csv(&$page, $eid = null, $item_id = null)
+    function handler_csv($page, $eid = null, $item_id = null)
     {
         $this->load('xnetevents.inc.php');
 
@@ -277,27 +335,65 @@ class XnetEventsModule extends PLModule
             return PL_NOT_FOUND;
         }
 
-        header('Content-type: text/x-csv; encoding=UTF-8');
-        header('Pragma: ');
-        header('Cache-Control: ');
-
+        pl_cached_content_headers('text/x-csv', 'iso-8859-1', 1);
         $page->changeTpl('xnetevents/csv.tpl', NO_SKIN);
 
         $admin = may_update();
+        $tri = (Env::v('order') == 'alpha' ? UserFilter::sortByPromo() : UserFilter::sortByName());
+        $all = !Env::v('item_id', false);
 
-        $tri = (Env::v('order') == 'alpha' ? 'promo, nom, prenom' : 'nom, prenom, promo');
-
-        $page->assign('participants',
-                      get_event_participants($evt, $item_id, $tri));
+        $participants = get_event_participants($evt, $item_id, $tri);
+        $title = 'Nom;Prénom;Promotion;Email';
+        if ($admin) {
+            $title .=';Société;Poste';
+        }
+        if ($all) {
+            foreach ($evt['moments'] as $moment) {
+                $title .= ';' . $moment['titre'];
+            }
+        }
+        if ($admin && $evt['money']) {
+            $title .= ';À payer;';
+            if ($evt['paiement_id']) {
+                $title .= 'Télépaiement;Liquide/Chèque;';
+            }
+            $title .= 'Payé';
+        } else {
+            $title .= ';Nombre';
+        } 
+        echo utf8_decode($title) . "\n";
+
+        if ($participants) {
+            foreach ($participants as $participant) {
+                $user = $participant['user'];
+                $line = $user->lastName() . ';' . $user->firstName() . ';' . $user->promo() . ';' . $user->bestEmail();
+                if ($admin && $user->hasProfile()) {
+                    $line .= ';' . $user->profile()->getMainJob()->company->name . ';' . $user->profile()->getMainJob()->description;
+                } else  {
+                    $line .= ';;';
+                }
+                if ($all) {
+                    foreach ($evt['moments'] as $moment) {
+                        $line .= ';' . $participant[$moment['item_id']];
+                    }
+                }
+                if ($admin && $evt['money']) {
+                    $line .= ';' . $participant['montant'] . ';';
+                    if ($evt['paiement_id']) {
+                        $line .= $participant['telepayment'] . ';' . $participant['adminpaid'] . ';';
+                    }
+                    $line .= $participant['paid'];
+                } else {
+                    $line .= ';' . $participant['nb'];
+                }
 
-        $page->assign('admin', $admin);
-        $page->assign('moments', $evt['moments']);
-        $page->assign('money', $evt['money']);
-        $page->assign('telepayment', $evt['paiement_id']);
-        $page->assign('tout', !Env::v('item_id', false));
+                echo utf8_decode($line) . "\n";
+            }
+        }
+        exit();
     }
 
-    function handler_ical(&$page, $eid = null)
+    function handler_ical($page, $eid = null)
     {
         global $globals;
 
@@ -321,22 +417,22 @@ class XnetEventsModule extends PLModule
         $page->assign('admin', may_update());
 
         if (may_update()) {
-            $page->assign('participants', get_event_participants($evt, null, 'promo, nom, prenom'));
+            $page->assign('participants', get_event_participants($evt, null, UserFilter::sortByPromo()));
         }
         $page->register_function('display_ical', 'display_ical');
         $page->assign_by_ref('e', $evt);
 
-        header('Content-Type: text/calendar; charset=utf-8');
+        pl_content_headers("text/calendar");
     }
 
-    function handler_edit(&$page, $eid = null)
+    function handler_edit($page, $eid = null)
     {
         global $globals;
 
         // get eid if the the given one is a short name
         if (!is_null($eid) && !is_numeric($eid)) {
             $res = XDB::query("SELECT eid
-                                 FROM groupex.evenements
+                                 FROM group_events
                                 WHERE asso_id = {?} AND short_name = {?}",
                               $globals->asso('id'), $eid);
             if ($res->numRows()) {
@@ -347,7 +443,7 @@ class XnetEventsModule extends PLModule
         // check the event is in our group
         if (!is_null($eid)) {
             $res = XDB::query("SELECT short_name
-                                 FROM groupex.evenements
+                                 FROM group_events
                                 WHERE eid = {?} AND asso_id = {?}",
                               $eid, $globals->asso('id'));
             if ($res->numRows()) {
@@ -386,13 +482,13 @@ class XnetEventsModule extends PLModule
                 'short_name'       => $short_name,
             );
 
-            $trivial = array('intitule', 'descriptif', 'noinvite',
-                             'show_participants', 'accept_nonmembre', 'organisateur_uid');
+            $trivial = array('intitule', 'descriptif', 'noinvite', 'subscription_notification',
+                             'show_participants', 'accept_nonmembre', 'uid');
             foreach ($trivial as $k) {
                 $evt[$k] = Post::v($k);
             }
             if (!$eid) {
-                $evt['organisateur_uid'] = S::v('uid');
+                $evt['uid'] = S::v('uid');
             }
 
             if (Post::v('deadline')) {
@@ -404,63 +500,64 @@ class XnetEventsModule extends PLModule
             }
 
             // Store the modifications in the database
-            XDB::execute('REPLACE INTO groupex.evenements
-                SET eid={?}, asso_id={?}, organisateur_uid={?}, intitule={?},
-                    paiement_id = {?}, descriptif = {?}, debut = {?},
-                    fin = {?}, show_participants = {?}, short_name = {?},
-                    deadline_inscription = {?}, noinvite = {?},
-                    accept_nonmembre = {?}',
-                    $evt['eid'], $evt['asso_id'], $evt['organisateur_uid'],
-                    $evt['intitule'], $evt['paiement_id'], $evt['descriptif'],
-                    $evt['debut'], $evt['fin'], $evt['show_participants'],
-                    $evt['short_name'], $evt['deadline_inscription'],
-                    $evt['noinvite'], $evt['accept_nonmembre']);
+            XDB::execute('INSERT INTO  group_events (eid, asso_id, uid, intitule, paiement_id,
+                                                     descriptif, debut, fin, show_participants,
+                                                     short_name, deadline_inscription, noinvite,
+                                                     accept_nonmembre, subscription_notification)
+                               VALUES  ({?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?})
+              ON DUPLICATE KEY UPDATE  asso_id = VALUES(asso_id), uid = VALUES(uid), intitule = VALUES(intitule),
+                                       paiement_id = VALUES(paiement_id), descriptif = VALUES(descriptif), debut = VALUES(debut),
+                                       fin = VALUES(fin), show_participants = VALUES(show_participants), short_name = VALUES(short_name),
+                                       deadline_inscription = VALUES(deadline_inscription), noinvite = VALUES(noinvite),
+                                       accept_nonmembre = VALUES(accept_nonmembre), subscription_notification = VALUES(subscription_notification)',
+                         $evt['eid'], $evt['asso_id'], $evt['uid'],
+                         $evt['intitule'], $evt['paiement_id'], $evt['descriptif'],
+                         $evt['debut'], $evt['fin'], $evt['show_participants'],
+                         $evt['short_name'], $evt['deadline_inscription'],
+                         $evt['noinvite'], $evt['accept_nonmembre'], $evt['subscription_notification']);
 
             // if new event, get its id
             if (!$eid) {
                 $eid = XDB::insertId();
             }
 
-            $nb_moments   = 0;
-            $money_defaut = 0;
-
             foreach ($moments as $i) {
-                if (Post::v('titre'.$i)) {
+                if (Post::v('titre' . $i)) {
                     $nb_moments++;
 
-                    $montant = strtr(Post::v('montant'.$i), ',', '.');
+                    $montant = strtr(Post::v('montant' . $i), ',', '.');
                     $money_defaut += (float)$montant;
-                    XDB::execute("
-                        REPLACE INTO groupex.evenements_items
-                        VALUES ({?}, {?}, {?}, {?}, {?})",
-                        $eid, $i, Post::v('titre'.$i),
-                        Post::v('details'.$i), $montant);
+                    XDB::execute('INSERT INTO  group_event_items (eid, item_id, titre, details, montant)
+                                       VALUES  ({?}, {?}, {?}, {?}, {?})
+                      ON DUPLICATE KEY UPDATE  titre = VALUES(titre), details = VALUES(details), montant = VALUES(montant)',
+                                 $eid, $i, Post::v('titre' . $i), Post::v('details' . $i), $montant);
                 } else {
-                    XDB::execute("DELETE FROM groupex.evenements_items
-                                            WHERE eid = {?} AND item_id = {?}", $eid, $i);
+                    XDB::execute('DELETE FROM  group_event_items
+                                        WHERE  eid = {?} AND item_id = {?}', $eid, $i);
                 }
             }
             // request for a new payment
             if (Post::v('paiement_id') == -1 && $money_defaut >= 0) {
-                require_once 'validations.inc.php';
-                $p = new PayReq(S::v('uid'),
-                                Post::v('intitule')." - ".$globals->asso('nom'),
+                $p = new PayReq(S::user(),
+                                $globals->asso('nom')." - ".Post::v('intitule'),
                                 Post::v('site'), $money_defaut,
                                 Post::v('confirmation'), 0, 999,
-                                $globals->asso('id'), $eid);
+                                $globals->asso('id'), $eid, Post::v('payment_public') == 'yes');
                 if ($p->accept()) {
                     $p->submit();
                 } else {
-                    $page->assign('paiement_message', Post::v('confirmation'));
-                    $page->assign('paiement_site', Post::v('site'));
+                    $page->assign('payment_message', Post::v('confirmation'));
+                    $page->assign('payment_site', Post::v('site'));
+                    $page->assign('payment_public', Post::v('payment_public') == 'yes');
+                    $page->assign('error', true);
                     $error = true;
                 }
             }
 
-            // events with no sub-event: add a sub-event with no name
+            // events with no sub-event: add a sub-event with default name
             if ($nb_moments == 0) {
-                XDB::execute("INSERT INTO groupex.evenements_items
-                                   VALUES ({?}, {?}, '', '', 0)", $eid, 1);
+                XDB::execute("INSERT INTO group_event_items
+                                   VALUES ({?}, {?}, 'Événement', '', 0)", $eid, 1);
             }
 
             if (!$error) {
@@ -469,9 +566,10 @@ class XnetEventsModule extends PLModule
         }
 
         // get a list of all the payment for this asso
-        $res = XDB::iterator("SELECT id, text
-                                FROM {$globals->money->mpay_tprefix}paiements
-                               WHERE asso_id = {?}", $globals->asso('id'));
+        $res = XDB::iterator("SELECT  id, text
+                                FROM  payments
+                               WHERE  asso_id = {?} AND NOT FIND_IN_SET('old', flags)",
+                             $globals->asso('id'));
         $paiements = array();
         while ($a = $res->next()) $paiements[$a['id']] = $a['text']; {
             $page->assign('paiements', $paiements);
@@ -480,17 +578,17 @@ class XnetEventsModule extends PLModule
         // when modifying an old event retreive the old datas
         if ($eid) {
             $res = XDB::query(
-                    "SELECT    eid, intitule, descriptif, debut, fin, organisateur_uid,
-                            show_participants, paiement_id, short_name,
-                            deadline_inscription, noinvite, accept_nonmembre
-                       FROM    groupex.evenements
+                    "SELECT  eid, intitule, descriptif, debut, fin, uid,
+                             show_participants, paiement_id, short_name,
+                             deadline_inscription, noinvite, accept_nonmembre, subscription_notification
+                       FROM  group_events
                       WHERE eid = {?}", $eid);
             $evt = $res->fetchOneAssoc();
             // find out if there is already a request for a payment for this event
-            require_once 'validations.inc.php';
-            $res = XDB::query("SELECT stamp FROM requests
-                                WHERE type = 'paiements' AND data LIKE {?}",
-                               PayReq::same_event($eid, $globals->asso('id')));
+            $res = XDB::query("SELECT  stamp
+                                 FROM  requests
+                                WHERE  type = 'paiements' AND data LIKE {?}",
+                              PayReq::same_event($eid, $globals->asso('id')));
             $stamp = $res->fetchOneCell();
             if ($stamp) {
                 $evt['paiement_id']  = -2;
@@ -499,10 +597,10 @@ class XnetEventsModule extends PLModule
             $page->assign('evt', $evt);
             // get all the different moments infos
             $res = XDB::iterator(
-                    "SELECT item_id, titre, details, montant
-                       FROM groupex.evenements_items AS ei
-                 INNER JOIN groupex.evenements AS e ON(e.eid = ei.eid)
-                      WHERE e.eid = {?}
+                    "SELECT  item_id, titre, details, montant
+                       FROM  group_event_items AS ei
+                 INNER JOIN  group_events AS e ON(e.eid = ei.eid)
+                      WHERE  e.eid = {?}
                    ORDER BY item_id", $eid);
             $items = array();
             while ($item = $res->next()) {
@@ -513,7 +611,7 @@ class XnetEventsModule extends PLModule
         $page->assign('url_ref', $eid);
     }
 
-    function handler_admin(&$page, $eid = null, $item_id = null)
+    function handler_admin($page, $eid = null, $item_id = null)
     {
         global $globals;
 
@@ -532,46 +630,70 @@ class XnetEventsModule extends PLModule
         if (may_update() && Post::v('adm')) {
             S::assert_xsrf_token();
 
-            $member = get_infos(Post::v('mail'));
+            $member = User::getSilent(Post::v('mail'));
             if (!$member) {
                 $page->trigError("Membre introuvable");
             }
 
             // change the price paid by a participant
             if (Env::v('adm') == 'prix' && $member) {
-                XDB::execute("UPDATE groupex.evenements_participants
-                                 SET paid = IF(paid + {?} > 0, paid + {?}, 0)
-                               WHERE uid = {?} AND eid = {?} AND item_id = 1",
-                        strtr(Env::v('montant'), ',', '.'),
-                        strtr(Env::v('montant'), ',', '.'),
-                        $member['uid'], $evt['eid']);
+                $amount = strtr(Env::v('montant'), ',', '.');
+                XDB::execute("UPDATE group_event_participants
+                                 SET paid = paid + {?}
+                               WHERE uid = {?} AND eid = {?} AND nb > 0
+                            ORDER BY item_id ASC
+                               LIMIT 1",
+                             $amount, $member->uid, $evt['eid']);
+                subscribe_lists_event($member->uid, $evt['short_name'], 1, $amount);
             }
 
             // change the number of personns coming with a participant
             if (Env::v('adm') == 'nbs' && $member) {
-                $res = XDB::query("SELECT paid
-                                     FROM groupex.evenements_participants
+                $res = XDB::query("SELECT SUM(paid)
+                                     FROM group_event_participants
                                     WHERE uid = {?} AND eid = {?}",
-                                  $member['uid'], $evt['eid']);
+                                  $member->uid, $evt['eid']);
+
+                $paid = $res->fetchOneCell();
+
+                // Ensure we have an integer
+                if ($paid == null) {
+                    $paid = 0;
+                }
 
-                $paid = intval($res->fetchOneCell());
                 $nbs  = Post::v('nb', array());
 
+                $paid_inserted = false;
                 foreach ($nbs as $id => $nb) {
                     $nb = max(intval($nb), 0);
-                    XDB::execute("REPLACE INTO groupex.evenements_participants
-                                        VALUES ({?}, {?}, {?}, {?}, {?}, {?})",
-                                  $evt['eid'], $member['uid'], $id, $nb, '', $id == 1 ? $paid : 0);
+                    if (!$paid_inserted && $nb > 0) {
+                        $item_paid = $paid;
+                        $paid_inserted = true;
+                    } else {
+                        $item_paid = 0;
+                    }
+                    XDB::execute('INSERT INTO  group_event_participants (eid, uid, item_id, nb, flags, paid)
+                                       VALUES  ({?}, {?}, {?}, {?}, {?}, {?})
+                      ON DUPLICATE KEY UPDATE  nb = VALUES(nb), flags = VALUES(flags), paid = VALUES(paid)',
+                                 $evt['eid'], $member->uid, $id, $nb, '', $item_paid);
                 }
 
-                $res = XDB::query("SELECT COUNT(uid) AS cnt, SUM(nb) AS nb
-                                     FROM groupex.evenements_participants
-                                    WHERE uid = {?} AND eid = {?}
-                                 GROUP BY uid",
-                                            $member['uid'], $evt['eid']);
+                $res = XDB::query('SELECT  COUNT(uid) AS cnt, SUM(nb) AS nb
+                                     FROM  group_event_participants
+                                    WHERE  uid = {?} AND eid = {?}
+                                 GROUP BY  uid',
+                                  $member->uid, $evt['eid']);
                 $u = $res->fetchOneAssoc();
-                $u = $u['cnt'] ? $u['nb'] : null;
-                subscribe_lists_event($u, $member['uid'], $evt);
+                if ($paid == 0 && Post::v('cancel')) {
+                    XDB::execute("DELETE FROM group_event_participants
+                                        WHERE uid = {?} AND eid = {?}",
+                                    $member->uid, $evt['eid']);
+                    $u = 0;
+                    subscribe_lists_event($member->uid, $evt['short_name'], -1, $paid);
+                } else {
+                    $u = $u['cnt'] ? $u['nb'] : null;
+                    subscribe_lists_event($member->uid, $evt['short_name'], ($u > 0 ? 1 : 0), $paid);
+                }
             }
 
             $evt = get_event_detail($eid, $item_id);
@@ -584,88 +706,49 @@ class XnetEventsModule extends PLModule
             $page->assign('moments', $evt['moments']);
         }
 
-        $tri = (Env::v('order') == 'alpha' ? 'promo, nom, prenom' : 'nom, prenom, promo');
-        $whereitemid = is_null($item_id) ? '' : "AND ep.item_id = $item_id";
-        $res = XDB::iterRow(
-                    'SELECT  UPPER(SUBSTRING(IF(u.nom IS NULL, m.nom,
-                                                IF(u.nom_usage<>"", u.nom_usage, u.nom)), 1, 1)),
-                             COUNT(DISTINCT ep.uid)
-                       FROM  groupex.evenements_participants AS ep
-                 INNER JOIN  groupex.evenements AS e ON (ep.eid = e.eid)
-                  LEFT JOIN  groupex.membres AS m ON ( ep.uid = m.uid AND e.asso_id = m.asso_id)
-                  LEFT JOIN  auth_user_md5   AS u ON ( u.user_id = ep.uid )
-                      WHERE  ep.eid = {?} '.$whereitemid . '
-                   GROUP BY  UPPER(SUBSTRING(IF(u.nom IS NULL,m.nom,u.nom), 1, 1))', $evt['eid']);
-
-        $alphabet = array();
-        $nb_tot = 0;
-        while (list($char, $nb) = $res->next()) {
-            $alphabet[ord($char)] = $char;
-            $nb_tot += $nb;
-            if (Env::has('initiale') && $char == strtoupper(Env::v('initiale'))) {
-                $tot = $nb;
-            }
-        }
-        ksort($alphabet);
-        $page->assign('alphabet', $alphabet);
-
         if ($evt['paiement_id']) {
-            $res = XDB::iterator(
-                "SELECT IF(u.nom_usage<>'', u.nom_usage, u.nom) AS nom, u.prenom,
-                        u.promo, a.alias AS email, t.montant
-                   FROM {$globals->money->mpay_tprefix}transactions AS t
-             INNER JOIN auth_user_md5 AS u ON(t.uid = u.user_id)
-             INNER JOIN aliases AS a ON (a.id = t.uid AND a.type='a_vie' )
-              LEFT JOIN groupex.evenements_participants AS ep ON(ep.uid = t.uid AND ep.eid = {?})
-                  WHERE t.ref = {?} AND ep.uid IS NULL",
-                  $evt['eid'], $evt['paiement_id']);
-            $page->assign('oublis', $res->total());
-            $page->assign('oubliinscription', $res);
-        }
-
-        $absents = XDB::iterator("SELECT  p.uid,
-                                          IF(m.origine = 'X', IF(u.nom_usage != '', u.nom_usage, u.nom), m.nom) AS nom,
-                                          IF(m.origine = 'X', u.prenom, u.prenom) AS prenom,
-                                          IF(m.origine = 'X', u.promo, m.origine) AS promo,
-                                          IF(m.origine = 'X', FIND_IN_SET('femme', u.flags), m.sexe) AS sexe,
-                                          IF(m.origine = 'X', a.alias, m.email) AS email
-                                    FROM  groupex.evenements_participants AS p
-                              INNER JOIN  groupex.membres                 AS m USING(uid)
-                               LEFT JOIN  groupex.evenements_participants AS p2 ON (p2.uid = m.uid AND p2.eid = p.eid
-                                                                                    AND p2.nb != 0)
-                               LEFT JOIN  auth_user_md5                   AS u ON (u.user_id = m.uid)
-                               LEFT JOIN  aliases                         AS a ON (a.id = u.user_id AND a.type = 'a_vie')
-                                   WHERE  p.eid = {?} AND p2.eid IS NULL
-                                       " . (Env::v('initiale') ? " AND IF(u.nom IS NULL, m.nom,
-                                          IF(u.nom_usage<>'', u.nom_usage, u.nom)) LIKE '" . Env::v('initiale') . "%'"
-                                         : "") . "
-                                GROUP BY  m.uid
-                                ORDER BY  nom, prenom, promo", $evt['eid']);
-
-        $ofs   = Env::i('offset');
-        $tot   = (Env::v('initiale') ? $tot : $nb_tot) - $absents->total();
-        $nbp   = intval(($tot-1)/NB_PER_PAGE);
-        $links = array();
-        if ($ofs) {
-            $links['précédent'] = $ofs-1;
-        }
-        for ($i = 0; $i <= $nbp; $i++) {
-            $links[(string)($i+1)] = $i;
-        }
-        if ($ofs < $nbp) {
-            $links['suivant'] = $ofs+1;
-        }
-        if (count($links)>1) {
+            $infos = User::getBulkUsersWithUIDs(
+                            XDB::fetchAllAssoc('SELECT  t.uid, t.amount
+                                                  FROM  payment_transactions AS t
+                                             LEFT JOIN  group_event_participants AS ep ON(ep.uid = t.uid AND ep.eid = {?})
+                                                 WHERE  t.status = "confirmed" AND t.ref = {?} AND ep.uid IS NULL',
+                                               $evt['eid'], $evt['paiement_id']),
+                            'uid', 'user');
+            $page->assign('oublis', count($infos));
+            $page->assign('oubliinscription', $infos);
+        }
+
+        $absents = User::getBulkUsersFromDB('SELECT  p.uid
+                                               FROM  group_event_participants AS p
+                                          LEFT JOIN  group_event_participants AS p2 ON (p2.uid = p.uid
+                                                                                               AND p2.eid = p.eid
+                                                                                               AND p2.nb != 0)
+                                              WHERE  p.eid = {?} AND p2.eid IS NULL
+                                           GROUP BY  p.uid', $evt['eid']);
+
+        $ofs = Env::i('offset');
+        $part = get_event_participants($evt, $item_id, UserFilter::sortByName(),
+                                       NB_PER_PAGE, $ofs * NB_PER_PAGE);
+
+        $nbp = ceil($evt['user_count'] / NB_PER_PAGE);
+        if ($nbp > 1) {
+            $links = array();
+            if ($ofs) {
+                $links['précédent'] = $ofs - 1;
+            }
+            for ($i = 1 ; $i <= $nbp; $i++) {
+                $links[(string)$i] = $i - 1;
+            }
+            if ($ofs < $nbp - 1) {
+                $links['suivant'] = $ofs+1;
+            }
             $page->assign('links', $links);
         }
 
-
         $page->assign('absents', $absents);
-        $page->assign('participants',
-                      get_event_participants($evt, $item_id, $tri,
-                                             "LIMIT ".($ofs*NB_PER_PAGE).", ".NB_PER_PAGE));
+        $page->assign('participants', $part);
     }
 }
 
-// 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:
 ?>