Handles canceled payment transactions.
[platal.git] / modules / payment.php
index c07a95c..4fa0641 100644 (file)
@@ -1,6 +1,6 @@
 <?php
 /***************************************************************************
- *  Copyright (C) 2003-2010 Polytechnique.org                              *
+ *  Copyright (C) 2003-2014 Polytechnique.org                              *
  *  http://opensource.polytechnique.org/                                   *
  *                                                                         *
  *  This program is free software; you can redistribute it and/or modify   *
  ***************************************************************************/
 
 /* sort en affichant une erreur */
-function cb_erreur($text) {
+function cb_erreur($text, $conf_title="") {
     global $globals;
-    echo "Error.\n";
+    echo "Error: ".$text."\n";
     $mymail = new PlMailer();
     $mymail->addTo($globals->money->email);
     $mymail->setFrom("webmaster@" . $globals->mail->domain);
     $mymail->setSubject("erreur lors d'un télépaiement (CyberPaiement)");
-    $mymail->setTxtBody("\n\n".var_export($_REQUEST,true));
+    $content = "raison de l'erreur : " . $text . "\n";
+    if ($conf_title != "") {
+        $content = $content."paiement : ".$conf_title."\n";
+    }
+    $content = $content . "dump de REQUEST :\n" . var_export($_REQUEST, true);
+    $mymail->setTxtBody($content);
     $mymail->send();
     echo "Notification sent.\n";
     exit;
@@ -45,7 +50,10 @@ function paypal_erreur($text, $send=true)
     $mymail->addTo($globals->money->email);
     $mymail->setFrom("webmaster@" . $globals->mail->domain);
     $mymail->setSubject("erreur lors d'un télépaiement (PayPal)");
-    $mymail->setTxtBody("\n\n".var_export($_REQUEST,true));
+    $mymail->setTxtBody("raison de l'erreur : ".$text."\n".
+                        "paiement : $conf_title \n\n".
+                        "dump de REQUEST :\n".
+                        var_export($_REQUEST,true));
     $mymail->send();
 
     Platal::page()->trigError($text);
@@ -105,185 +113,122 @@ class PaymentModule extends PLModule
     function handlers()
     {
         return array(
-            'payment'                      => $this->make_hook('payment',          AUTH_MDP,    'payment'),
-            'payment/cyber_return'         => $this->make_hook('cyber_return',     AUTH_PUBLIC, 'user', NO_HTTPS),
+            'payment'                      => $this->make_hook('payment',          AUTH_PUBLIC, 'user'),
             'payment/cyber2_return'        => $this->make_hook('cyber2_return',    AUTH_PUBLIC, 'user', NO_HTTPS),
             'payment/paypal_return'        => $this->make_hook('paypal_return',    AUTH_PUBLIC, 'user', NO_HTTPS),
-            '%grp/paiement'                => $this->make_hook('xnet_payment',     AUTH_MDP),
-            '%grp/payment'                 => $this->make_hook('xnet_payment',     AUTH_MDP),
-            '%grp/payment/cyber_return'    => $this->make_hook('cyber_return',     AUTH_PUBLIC, 'user', NO_HTTPS),
+            '%grp/paiement'                => $this->make_hook('xnet_payment',     AUTH_PUBLIC, 'user'),
+            '%grp/payment'                 => $this->make_hook('xnet_payment',     AUTH_PUBLIC, 'user'),
+            '%grp/payment/csv'             => $this->make_hook('payment_csv',      AUTH_PASSWD, 'groupadmin'),
             '%grp/payment/cyber2_return'   => $this->make_hook('cyber2_return',    AUTH_PUBLIC, 'user', NO_HTTPS),
             '%grp/payment/paypal_return'   => $this->make_hook('paypal_return',    AUTH_PUBLIC, 'user', NO_HTTPS),
-            'admin/payments'               => $this->make_hook('admin',            AUTH_MDP,    'admin'),
-            'admin/payments/methods'       => $this->make_hook('adm_methods',      AUTH_MDP,    'admin'),
-            'admin/payments/transactions'  => $this->make_hook('adm_transactions', AUTH_MDP,    'admin'),
-            'admin/reconcile'              => $this->make_hook('adm_reconcile',    AUTH_MDP,    'admin'),
-            'admin/reconcile/importlogs'   => $this->make_hook('adm_importlogs',   AUTH_MDP,    'admin'),
-            'admin/reconcile/transfers'    => $this->make_hook('adm_transfers',    AUTH_MDP,    'admin'),
-            'admin/reconcile/bankaccounts' => $this->make_hook('adm_bankaccounts', AUTH_MDP,    'admin'),
+            'admin/payments'               => $this->make_hook('admin',            AUTH_PASSWD, 'admin'),
+            'admin/payments/methods'       => $this->make_hook('adm_methods',      AUTH_PASSWD, 'admin'),
+            'admin/payments/transactions'  => $this->make_hook('adm_transactions', AUTH_PASSWD, 'admin'),
+            'admin/reconcile'              => $this->make_hook('adm_reconcile',    AUTH_PASSWD, 'admin'),
+            'admin/reconcile/importlogs'   => $this->make_hook('adm_importlogs',   AUTH_PASSWD, 'admin'),
+            'admin/reconcile/transfers'    => $this->make_hook('adm_transfers',    AUTH_PASSWD, 'admin'),
+            'admin/payments/bankaccounts'  => $this->make_hook('adm_bankaccounts', AUTH_PASSWD, 'admin'),
         );
     }
 
-    function handler_payment(&$page, $ref = -1)
+    function handler_payment($page, $ref = -1)
     {
-        global $globals;
-
+        $page->changeTpl('payment/payment.tpl');
+        $page->setTitle('Télépaiement');
         $this->load('money.inc.php');
 
-        if (!empty($GLOBALS['IS_XNET_SITE'])) {
-            if (!$globals->asso('id')) {
-                return PL_NOT_FOUND;
-            }
-            $res = XDB::query('SELECT  asso_id
-                                 FROM  payments
-                                WHERE  asso_id = {?} AND id = {?}',
-                              $globals->asso('id'), $ref);
-            if (!$res->numRows()) {
-                return PL_FORBIDDEN;
-            }
-        }
-        $page->changeTpl('payment/index.tpl');
-        $page->setTitle('Télépaiements');
-
-        // initialisation
-        $op   = Env::v('op', 'select');
         $meth = new PayMethod(Env::i('methode', -1));
         $pay  = new Payment($ref);
 
-        if($pay->flags->hasflag('old')){
-            $page->trigError("La transaction selectionnée est périmée.");
-            $pay = new Payment();
+        if (!$pay->flags->hasflag('public') && (!S::user() || !S::logged())) {
+            $page->kill("Vous n'avez pas les permissions nécessaires pour accéder à cette page.");
+        } else {
+            $page->assign('public', true);
         }
-        $val = Env::v('montant') != 0 ? Env::v('montant') : $pay->amount_def;
 
-        if (($e = $pay->check($val)) !== true) {
-            $page->trigError($e);
+        if ($pay->flags->hasflag('old')) {
+            $page->kill('La transaction selectionnée est périmée.');
         }
 
-        if ($op == 'submit') {
-            $pay->init($val, $meth);
-            $pay->prepareform($pay);
-        } else {
-            $res = XDB::iterator('SELECT  timestamp, amount
+        if (Env::has('montant')) {
+            $pay->amount_def = Env::v('montant');
+        }
+        $val = (Post::v('amount') != 0) ? Post::v('amount') : $pay->amount_def;
+
+        if (($error = $pay->check($val)) !== true) {
+            $page->trigError($error);
+        }
+
+        if (Post::has('op') && Post::v('op', 'select') == 'submit') {
+            if (S::logged()) {
+                $user = S::user();
+            } else {
+                $user = User::getSilent(Post::t('login'));
+            }
+
+            if (is_null($user)) {
+                $page->trigError("L'identifiant est erroné.");
+                $page->assign('login_error', true);
+                $page->assign('login', Post::t('login'));
+            } else {
+                $pay->init($val, $meth);
+                $pay->prepareform($user);
+                $page->assign('full_name', $user->fullName(true));
+                $page->assign('sex', $user->isFemale());
+            }
+        } elseif (S::logged()) {
+            $res = XDB::iterator('SELECT  ts_confirmed, amount
                                     FROM  payment_transactions
                                    WHERE  uid = {?} AND ref = {?}
-                                ORDER BY  timestamp DESC',
-                                 S::v('uid', -1), $ref);
+                                ORDER BY  ts_confirmed DESC',
+                                 S::v('uid', -1), $pay->id);
 
             if ($res->total()) {
                 $page->assign('transactions', $res);
             }
+
+            // Only if $id = -1, meaning only for donation the site's association
+            if ($ref == -1) {
+                $biggest_donations = XDB::fetchAllAssoc('SELECT  IF(p.display,
+                                                                    IF(ap.pid IS NOT NULL, CONCAT(a.full_name, \' (\', pd.promo, \')\'), a.full_name),
+                                                                    \'XXXX\') AS name, p.amount, p.ts_confirmed
+                                                           FROM  payment_transactions AS p
+                                                     INNER JOIN  accounts             AS a  ON (a.uid = p.uid)
+                                                      LEFT JOIN  account_profiles     AS ap ON (a.uid = ap.uid AND FIND_IN_SET(\'owner\', ap.perms))
+                                                      LEFT JOIN  profile_display      AS pd ON (ap.pid = pd.pid)
+                                                          WHERE  p.ref = {?}
+                                                       ORDER BY  LENGTH(p.amount) DESC, p.amount DESC, name
+                                                          LIMIT  10',
+                                                        $pay->id);
+
+                $donations = XDB::fetchAllAssoc('(SELECT  SUM(amount) AS amount, YEAR(ts_confirmed) AS year, MONTH(ts_confirmed) AS month, ts_confirmed
+                                                    FROM  payment_transactions
+                                                   WHERE  ref = {?} AND YEAR(ts_confirmed) = YEAR(CURDATE())
+                                                GROUP BY  month)
+                                                 UNION
+                                                 (SELECT  SUM(amount) AS amount, YEAR(ts_confirmed) AS year, 0 AS month, ts_confirmed
+                                                    FROM  payment_transactions
+                                                   WHERE  ref = {?} AND YEAR(ts_confirmed) < YEAR(CURDATE())
+                                                GROUP BY  year)
+                                                ORDER BY  year DESC, month DESC',
+                                                $pay->id, $pay->id);
+
+                $page->assign('biggest_donations', $biggest_donations);
+                $page->assign('donations', $donations);
+                $page->assign('donation', true);
+            }
         }
 
-        $val = floor($val) . '.' . substr(floor(($val - floor($val)) * 100 + 100), 1);
-        $page->assign('montant', $val);
+        $val = floor($val * 100) / 100;
+        $page->assign('amount', $val);
         $page->assign('comment', Env::v('comment'));
 
         $page->assign('meth', $meth);
         $page->assign('pay', $pay);
         $page->assign('evtlink', $pay->event());
-        $page->assign('sex', S::user()->isFemale());
-    }
-
-    function handler_cyber_return(&$page, $uid = null)
-    {
-        /* reference banque (numero de transaction) */
-        $champ901 = Env::s('CHAMP901');
-        /* cle d'acceptation */
-        $champ905 = Env::s('CHAMP905');
-        /* code retour */
-        $champ906 = Env::s('CHAMP906');
-        /* email renvoye par la banque */
-        $champ104 = Env::s('CHAMP104');
-        /* reference complete de la commande */
-        $champ200 = Env::s('CHAMP200');
-        /* montant de la transaction */
-        $champ201 = Env::s('CHAMP201');
-        /* devise */
-        $champ202 = Env::s('CHAMP202');
-        $montant = "$champ201 $champ202";
-
-        /* on extrait les informations sur l'utilisateur */
-        $user = User::get($uid);
-        if (!$user) {
-            cb_erreur("uid invalide");
-        }
-
-
-        /* on extrait la reference de la commande */
-        if (!ereg('-xorg-([0-9]+)$', $champ200, $matches)) {
-            cb_erreur("référence de commande invalide");
-        }
-
-        echo ($ref = $matches[1]);
-        $res = XDB::query('SELECT  mail, text, confirmation
-                             FROM  payments
-                            WHERE  id = {?}', $ref);
-        if (!list($conf_mail, $conf_title, $conf_text) = $res->fetchOneRow()) {
-            cb_erreur("référence de commande inconnue");
-        }
-
-        /* on extrait le code de retour */
-        if ($champ906 != "0000") {
-            $res = XDB::query('SELECT  rcb.text, c.id, c.text
-                                 FROM  payment_codeRCB AS rcb
-                            LEFT JOIN  payment_codeC   AS c ON (rcb.codeC = c.id)
-                                WHERE  rcb.id = {?}', $champ906);
-            if (list($rcb_text, $c_id, $c_text) = $res->fetchOneRow()) {
-                cb_erreur("erreur lors du paiement : $c_text ($c_id)");
-            } else{
-                cb_erreur("erreur inconnue lors du paiement");
-            }
-        }
-
-        /* on fait l'insertion en base de donnees */
-        XDB::execute('INSERT INTO  payment_transactions (id, uid, ref, fullref, amount, pkey, comment)
-                           VALUES  ({?}, {?}, {?}, {?}, {?}, {?}, {?})',
-                     $champ901, $user->id(), $ref, $champ200, $montant, $champ905, Env::v('comment'));
-
-        // We check if it is an Xnet payment and then update the related ML.
-        $res = XDB::query('SELECT  eid
-                             FROM  group_events
-                            WHERE  paiement_id = {?}', $ref);
-        if ($eid = $res->fetchOneCell()) {
-            require_once dirname(__FILE__) . '/xnetevents/xnetevents.inc.php';
-            $evt = get_event_detail($eid);
-            subscribe_lists_event($uid, $evt, 1, $montant, true);
-        }
-
-        /* on genere le mail de confirmation */
-        $conf_text = str_replace(
-            array('<prenom>', '<nom>', '<promo>', '<montant>', '<salutation>', '<cher>', '<comment>'),
-            array($user->firstName(), $user->lastName(), $user->promo(), $montant,
-                  $user->isFemale() ? 'Chère' : 'Cher', $user->isFemale() ? 'Chère' : 'Cher',
-                  Env::v('comment')), $conf_text);
-
-        global $globals;
-        $mymail = new PlMailer();
-        $mymail->setFrom($conf_mail);
-        $mymail->addCc($conf_mail);
-        $mymail->setSubject($conf_title);
-        $mymail->setWikiBody($conf_text);
-        $mymail->sendTo($user);
-
-        /* on envoie les details de la transaction à telepaiement@ */
-        $mymail = new PlMailer();
-        $mymail->setFrom("webmaster@" . $globals->mail->domain);
-        $mymail->addTo($globals->money->email);
-        $mymail->setSubject($conf_title);
-        $msg = 'utilisateur : ' . $user->login() . ' (' . $user->id() . ')' . "\n" .
-               'mail : ' . $user->forlifeEmail() . "\n\n" .
-               "paiement : $conf_title ($conf_mail)\n".
-               "reference : $champ200\n".
-               "montant : $montant\n\n".
-               "dump de REQUEST:\n".
-               var_export($_REQUEST,true);
-        $mymail->setTxtBody($msg);
-        $mymail->send();
-        exit;
     }
 
-    function handler_cyber2_return(&$page, $uid = null)
+    function handler_cyber2_return($page, $uid = null)
     {
         global $globals, $platal;
 
@@ -306,7 +251,7 @@ class PaymentModule extends PLModule
         }
 
         /* on extrait la reference de la commande */
-        if (!ereg('-([0-9]+)$', Env::v('vads_order_id'), $matches)) {
+        if (!preg_match('/-([0-9]+)$/', Env::v('vads_order_id'), $matches)) {
             cb_erreur("référence de commande invalide");
         }
 
@@ -323,19 +268,18 @@ class PaymentModule extends PLModule
         if (Env::v('vads_currency') != '978') {
             cb_erreur("monnaie autre que l'euro");
         }
-        $amount = ((float)Env::i('vads_amount')) / 100;
-        $montant = sprintf("%.02f EUR", $amount);
+        $montant = ((float)Env::i('vads_amount')) / 100;
 
         /* on extrait le code de retour */
         if (Env::v('vads_result') != '00') {
-            cb_erreur('erreur lors du paiement : ?? (' . Env::v('vads_result') . ')');
+            cb_erreur('erreur lors du paiement : ?? (' . Env::v('vads_result') . ')', $conf_title);
         }
 
         /* on fait l'insertion en base de donnees */
-        XDB::execute('INSERT INTO  payment_transactions (id, uid, ref, fullref, amount, pkey, comment)
-                           VALUES  ({?}, {?}, {?}, {?}, {?}, {?}, {?})',
-                     Env::v('vads_trans_date'), $user->id(), $ref, Env::v('vads_order_id'), $montant, '', Env::v('vads_order_info'));
-        echo "Paiement stored.\n";
+        XDB::execute('INSERT INTO  payment_transactions (id, method_id, uid, ref, fullref, ts_confirmed, amount, pkey, comment, status, display)
+                           VALUES  ({?}, 2, {?}, {?}, {?}, NOW(), {?}, {?}, {?}, "confirmed", {?})',
+                     Env::v('vads_trans_date'), $user->id(), $ref, Env::v('vads_order_id'), $montant, '', Env::v('vads_order_info'), Env::i('vads_order_info2'));
+        echo "Payment stored.\n";
 
         // We check if it is an Xnet payment and then update the related ML.
         $res = XDB::query('SELECT  eid, asso_id
@@ -345,7 +289,7 @@ class PaymentModule extends PLModule
             list($eid, $asso_id) = $res->fetchOneRow();
             require_once dirname(__FILE__) . '/xnetevents/xnetevents.inc.php';
             $evt = get_event_detail($eid, false, $asso_id);
-            subscribe_lists_event($user->id(), $evt, 1, $amount, true);
+            subscribe_lists_event($user->id(), $evt['short_name'], 1, $montant, true);
         }
 
         /* on genere le mail de confirmation */
@@ -353,7 +297,7 @@ class PaymentModule extends PLModule
             array('<prenom>', '<nom>', '<promo>', '<montant>', '<salutation>', '<cher>', '<comment>'),
             array($user->firstName(), $user->lastName(), $user->promo(), $montant,
                   $user->isFemale() ? 'Chère' : 'Cher', $user->isFemale() ? 'Chère' : 'Cher',
-                  Env::v('comment')), $conf_text);
+                  Env::v('vads_order_info')), $conf_text);
 
         global $globals;
         $mymail = new PlMailer();
@@ -381,7 +325,7 @@ class PaymentModule extends PLModule
         exit;
     }
 
-    function handler_paypal_return(&$page, $uid = null)
+    function handler_paypal_return($page, $uid = null)
     {
         $page->changeTpl('payment/retour_paypal.tpl');
 
@@ -394,12 +338,13 @@ class PaymentModule extends PLModule
         /* raison */
         $reason = ($status == 'Pending') ? Env::s('pending_reason') : Env::s('reason_code');
         /* reference complete de la commande */
-        $fullref = Env::s('cm');
+        $fullref = str_replace('%2d','-',Env::s('cm'));
         /* montant de la transaction */
-        $montant_nb = Env::s('amt');
+        $montant = Env::s('amt');
         /* devise */
-        $montant_dev = Env::s('cc');
-        $montant = "$montant_nb $montant_dev";
+        if (Env::s('cc') != 'EUR') {
+            cb_erreur("monnaie autre que l'euro");
+        }
 
         /* on extrait le code de retour */
         if ($status != "Completed") {
@@ -417,7 +362,7 @@ class PaymentModule extends PLModule
         }
 
         /* on extrait la reference de la commande */
-        if (!ereg('-xorg-([0-9]+)$', $fullref, $matches)) {
+        if (!preg_match('/-xorg-([0-9]+)$/', $fullref, $matches)) {
             paypal_erreur("référence de commande invalide");
         }
 
@@ -430,25 +375,26 @@ class PaymentModule extends PLModule
         }
 
         /* on fait l'insertion en base de donnees */
-        XDB::execute("INSERT INTO  payment_transactions (id, uid, ref, fullref, amount, pkey, comment)
-                           VALUES  ({?}, {?}, {?}, {?}, {?}, {?}, {?})",
-                    $no_transaction, $user->id(), $ref, $fullref, $montant, $clef, Env::v('comment'));
+        XDB::execute("INSERT INTO  payment_transactions (id, method_id, uid, ref, fullref, ts_confirmed, amount, pkey, comment, status, display)
+                           VALUES  ({?}, 1, {?}, {?}, {?}, NOW(), {?}, {?}, {?}, 'confirmed', {?})",
+                    $no_transaction, $user->id(), $ref, $fullref, $montant, $clef, Env::v('comment'), Get::i('display'));
 
         // We check if it is an Xnet payment and then update the related ML.
-        $res = XDB::query('SELECT  eid
+        $res = XDB::query('SELECT  eid, asso_id
                              FROM  group_events
                             WHERE  paiement_id = {?}', $ref);
-        if ($eid = $res->fetchOneCell()) {
+        if ($res->numRows() == 1) {
+            list($eid, $asso_id) = $res->fetchOneRow();
             require_once dirname(__FILE__) . '/xnetevents/xnetevents.inc.php';
-            $evt = get_event_detail($eid);
-            subscribe_lists_event($user->id(), $evt, 1, $montant, true);
+            $evt = get_event_detail($eid, false, $asso_id);
+            subscribe_lists_event($user->id(), $evt['short_name'], 1, $montant, true);
         }
 
         /* on genere le mail de confirmation */
-        $conf_text = str_replace(array('<prenom>', '<nom>', '<promo>', '<montant>', '<salutation>', '<cher>'),
+        $conf_text = str_replace(array('<prenom>', '<nom>', '<promo>', '<montant>', '<salutation>', '<cher>', '<comment>'),
                                  array($user->firstName(), $user->lastName(), $user->promo(), $montant,
-                                       $user->isFemale() ? 'Chère' : 'Cher',
-                                       $user->isFemale() ? 'Chère' : 'Cher'), $conf_text);
+                                       $user->isFemale() ? 'Chère' : 'Cher', $user->isFemale() ? 'Chère' : 'Cher',
+                                       Env::v('comment')), $conf_text);
 
         global $globals;
         $mymail = new PlMailer();
@@ -477,22 +423,30 @@ class PaymentModule extends PLModule
         $page->assign('erreur', $erreur);
     }
 
-    function handler_xnet_payment(&$page, $pid = null)
+    function handler_xnet_payment($page, $pid = null)
     {
         global $globals;
 
         $perms = S::v('perms');
-        if (!$perms->hasFlag('groupmember')) {
-            if (is_null($pid)) {
+        if (is_null($pid)) {
+            if (!(S::identified() && $perms->hasFlag('groupadmin'))) {
                 return PL_FORBIDDEN;
             }
-            $res = XDB::query("SELECT  1
-                                 FROM  group_events AS e
-                           INNER JOIN  group_event_participants AS ep ON (ep.eid = e.eid AND e.uid = {?})
-                                WHERE  e.paiement_id = {?} AND e.asso_id = {?}",
-                              S::i('uid'), $pid, $globals->asso('id'));
-            if ($res->numRows() == 0) {
-                return PL_FORBIDDEN;
+        } else {
+            if (!(S::identified() && $perms->hasFlag('groupmember'))) {
+                $res = XDB::query("SELECT  1
+                                     FROM  group_events AS e
+                               INNER JOIN  group_event_participants AS ep ON (ep.eid = e.eid AND ep.uid = {?})
+                                    WHERE  e.paiement_id = {?} AND e.asso_id = {?}",
+                                  S::i('uid'), $pid, $globals->asso('id'));
+                $public = XDB::query("SELECT  1
+                                        FROM  payments     AS p
+                                  INNER JOIN  group_events AS g ON (g.paiement_id = p.id)
+                                       WHERE  g.asso_id = {?} AND p.id = {?} AND FIND_IN_SET('public', p.flags)",
+                                     $globals->asso('id'), $pid);
+                if ($res->numRows() == 0 && $public->numRows() == 0) {
+                    return PL_FORBIDDEN;
+                }
             }
         }
 
@@ -512,7 +466,7 @@ class PaymentModule extends PLModule
         $trans = array();
         $event = array();
         if (may_update()) {
-            static $orders = array('timestamp' => 'p', 'directory_name' => 'a', 'promo' => 'pd', 'comment' => 'p', 'amount' => 'p');
+            static $orders = array('ts_confirmed' => 'p', 'directory_name' => 'a', 'promo' => 'pd', 'comment' => 'p', 'amount' => 'p');
 
             if (Get::has('order_id') && Get::has('order') && array_key_exists(Get::v('order'), $orders)) {
                 $order_id = Get::i('order_id');
@@ -539,7 +493,7 @@ class PaymentModule extends PLModule
         foreach($tit as $foo) {
             $pid = $foo['id'];
             if (may_update()) {
-                $res = XDB::query('SELECT  p.uid, IF(p.timestamp = \'0000-00-00\', 0, p.timestamp) AS date, p.comment, p.amount
+                $res = XDB::query('SELECT  p.uid, IF(p.ts_confirmed = \'0000-00-00\', 0, p.ts_confirmed) AS date, p.comment, p.amount
                                      FROM  payment_transactions AS p
                                INNER JOIN  accounts             AS a  ON (a.uid = p.uid)
                                 LEFT JOIN  account_profiles     AS ap ON (ap.uid = p.uid AND FIND_IN_SET(\'owner\', ap.perms))
@@ -549,11 +503,11 @@ class PaymentModule extends PLModule
                 $trans[$pid] = User::getBulkUsersWithUIDs($res->fetchAllAssoc(), 'uid', 'user');
                 $sum = 0;
                 foreach ($trans[$pid] as $i => $t) {
-                    $sum += strtr(substr($t['amount'], 0, strpos($t['amount'], 'EUR')), ',', '.');
-                    $trans[$pid][$i]['amount'] = str_replace('EUR', '€', $t['amount']);
+                    $sum += $t['amount'];
+                    $trans[$pid][$i]['amount'] = $t['amount'];
                 }
                 $trans[$pid][] = array('limit'  =>  true,
-                                       'amount' => strtr($sum, '.', ',') . ' €');
+                                       'amount' => $sum);
             }
             $res = XDB::iterRow("SELECT  e.eid, e.short_name, e.intitule, ep.nb, ei.montant, ep.paid
                                    FROM  group_events             AS e
@@ -574,45 +528,81 @@ class PaymentModule extends PLModule
                     $event[$pid]['paid']      = $paid;
                 }
             }
-            $res = XDB::query('SELECT  amount
+            $res = XDB::query('SELECT  SUM(amount) AS sum_amount
                                  FROM  payment_transactions
-                                WHERE  id = {?} AND uid = {?}', $pid, S::v('uid'));
-            $montants = $res->fetchColumn();
-
-            foreach ($montants as $m) {
-                $p = strtr(substr($m, 0, strpos($m, 'EUR')), ',', '.');
-                $event[$pid]['paid'] += trim($p);
-            }
+                                WHERE  ref = {?} AND uid = {?}', $pid, S::v('uid'));
+            $event[$pid]['paid'] = $res->fetchOneCell();
         }
         $page->register_modifier('decode_comment', 'decode_comment');
         $page->assign('trans', $trans);
         $page->assign('event', $event);
     }
 
-    function handler_admin(&$page, $action = 'list', $id = null) {
+    function handler_payment_csv($page, $pid = null)
+    {
+        if (is_null($pid)) {
+            pl_redirect('payment');
+        }
+        if (substr($pid, -4) == '.vcf') {
+            $pid = substr($pid, 0, strlen($pid) - 4);
+        }
+
+        $res = XDB::fetchAllAssoc('SELECT  uid, IF(ts_confirmed = \'0000-00-00\', 0, ts_confirmed) AS date, comment, amount
+                                     FROM  payment_transactions
+                                    WHERE  ref = {?}
+                                 ORDER BY  ts_confirmed',
+                                  $pid);
+        if (is_null($res)) {
+            pl_redirect('payment');
+        }
+
+        $users = User::getBulkUsersWithUIDs($res, 'uid', 'user');
+        $sum = 0;
+
+        pl_cached_content_headers('text/x-csv', 'iso-8859-1', 1);
+        $csv = fopen('php://output', 'w');
+        fputcsv($csv, array('Date', 'Nom', utf8_decode('Prénom'), 'Sexe', 'Promotion', 'Email', 'Commentaire', 'Montant'), ';');
+        foreach ($users as $item) {
+            $user = $item['user'];
+            $sum += $item['amount'];
+            fputcsv($csv, array(format_datetime($item['date'], '%d/%m/%y'), utf8_decode($user->lastName()), utf8_decode($user->firstName()),
+                                ($user->isFemale()) ? 'F' : 'M', $user->promo(), $user->ForlifeEmail(),
+                                utf8_decode($item['comment']), strtr($item['amount'], '.', ',') . ' EUR' ), ';');
+        }
+        fputcsv($csv, array(date('d/m/y'), 'Total', '', '', '' , '', '', strtr($sum, '.', ',') . ' EUR'), ';');
+
+        fclose($csv);
+        exit;
+    }
+
+    function handler_admin($page, $action = 'list', $id = null) {
         $page->setTitle('Administration - Paiements');
         $page->assign('title', 'Gestion des télépaiements');
         $table_editor = new PLTableEditor('admin/payments','payments','id');
-        //$table_editor->add_join_table('payment_transactions','ref',true); => on ne supprime jamais une transaction
         $table_editor->add_sort_field('flags');
         $table_editor->add_sort_field('id', true, true);
         $table_editor->on_delete("UPDATE payments SET flags = 'old' WHERE id = {?}", "Le paiement a été archivé");
         $table_editor->describe('text', 'intitulé', true);
-        $table_editor->describe('url', 'site web', false);
-        $table_editor->describe('amount_def', 'montant par défaut', false);
-        $table_editor->describe('amount_min', 'montant minimum', false);
-        $table_editor->describe('amount_max', 'montant maximum', false);
+        $table_editor->describe('url', 'site web', false, true);
+        $table_editor->describe('amount_def', 'montant par défaut', false, true);
+        $table_editor->describe('amount_min', 'montant minimum', false, true);
+        $table_editor->describe('amount_max', 'montant maximum', false, true);
         $table_editor->describe('mail', 'email contact', true);
-        $table_editor->describe('confirmation', 'message confirmation', false);
-
+        $table_editor->describe('confirmation', 'message confirmation', false, true);
+        $table_editor->describe('rib_id', 'RIB', false, true);
         // adds a column with the start date of the linked event if there is one
         $table_editor->add_option_table('group_events', 'group_events.paiement_id = t.id');
-        $table_editor->add_option_field('group_events.debut', 'related_event', 'évènement', 'timestamp');
+        $table_editor->add_option_field('group_events.archive', 'related_event', 'évènement archivé ?', 'tinyint');
+        // adds a column with the linked rib if there is one
+        $table_editor->add_option_table('payment_bankaccounts', 'payment_bankaccounts.id = t.rib_id');
+        $table_editor->add_option_field('payment_bankaccounts.owner', 'linked_rib_owner', 'rib associé', 'varchar');
+        // adds a link to the table of all the transactions
+        $table_editor->addLink('id', "admin/payments/transactions/");
 
         $table_editor->apply($page, $action, $id);
     }
 
-    function handler_adm_transactions(&$page, $payment_id = null, $action = "list", $id = null) {
+    function handler_adm_transactions($page, $payment_id = null, $action = "list", $id = null) {
         // show transactions. FIXME: should not be modifiable
         $page->setTitle('Administration - Paiements - Transactions');
         $page->assign('title', "Liste des transactions pour le paiement {$payment_id}");
@@ -620,34 +610,42 @@ class PaymentModule extends PLModule
         if ($payment_id == null)
             $page->trigError("Aucun ID de paiement fourni.");
 
-        $table_editor = new PLTableEditor("admin/transactions/{$payment_id}",'payment_transactions','id');
+        $table_editor = new PLTableEditor("admin/payments/transactions/{$payment_id}",'payment_transactions','id', true);
         $table_editor->set_where_clause(XDB::format('ref = {?}', $payment_id));
-        $table_editor->apply($page, 'list', $id); // only the 'list' action is allowed
-        $page->assign('readonly', 'readonly');     // don't show modification features
+        $table_editor->add_sort_field('id', true);
+        $table_editor->describe('ts_initiated', 'ts_initiated', true, false);
+        $table_editor->describe('commission', 'commission', true, false);
+        $table_editor->describe('pkey', 'pkey', true, true);
+        $table_editor->describe('comment', 'comment', true, true);
+        $table_editor->describe('recon_id', 'recon_id', true, false);
+        $table_editor->describe('display', 'display', true, true);
+        $table_editor->apply($page, $action, $id);
+        $page->assign('addonly', 'addonly');     // don't show modification features, only add feature
     }
 
-    function handler_adm_bankaccounts(&$page, $action = 'list', $id = null) {
+    function handler_adm_bankaccounts($page, $action = "list", $id = null) {
         // managment of bank account used for money transfert
         $page->setTitle('Administration - Paiements - RIBs');
         $page->assign('title', "Liste des RIBs");
 
         $table_editor = new PLTableEditor('admin/payments/bankaccounts', 'payment_bankaccounts', 'id');
-        $table_editor->describe('asso_id', 'ID du groupe', false);
+        $table_editor->describe('asso_id', 'ID du groupe', false, true);
         $table_editor->describe('owner', 'titulaire', true);
         $table_editor->add_option_table('groups', 'groups.id = t.asso_id');
-        $table_editor->add_option_field('groups.diminutif', 'group_name', 'groupe', 'varchar','account');
+        $table_editor->add_option_field('groups.diminutif', 'group_name', 'groupe', 'varchar','iban');
 
-        // check RIB key
+        /* check RIB key     FIXME: the column format (and name) changed
         if ($action == 'update' && Post::has('account') && !check_rib(Post::v('account'))) {
             $page->trigError("Le RIB n'est pas valide");
             $table_editor->apply($page, 'edit', $id);
             return;
         }
+        */
 
         $table_editor->apply($page, $action, $id);
     }
 
-    function handler_adm_methods(&$page, $action = 'list', $id = null) {
+    function handler_adm_methods($page, $action = "list", $id = null) {
         // show and edit payment methods
         $page->setTitle('Administration - Paiements - Méthodes');
         $page->assign('title', 'Méthodes de paiement');
@@ -655,7 +653,7 @@ class PaymentModule extends PLModule
         $table_editor->apply($page, $action, $id);
     }
 
-    function handler_adm_reconcile(&$page, $step = 'list', $param = null) {
+    function handler_adm_reconcile($page, $step = 'list', $param = null) {
         // reconciles logs with transactions
         // FIXME: the admin is considered to be fair => he doesn't hack the $step value, nor other params
         $page->setTitle('Administration - Paiements - Réconciliations');
@@ -687,6 +685,7 @@ class PaymentModule extends PLModule
 
             $recongps = array();
 
+            // récupère les réconciliations non groupées
             $res = XDB::query("SELECT  r.id, short_name AS method, period_start, period_end, status,
                                        payment_count, sum_amounts, sum_commissions
                                  FROM  payment_reconcilations AS r
@@ -696,10 +695,12 @@ class PaymentModule extends PLModule
             foreach ($res->fetchAllAssoc() as $recon)
                 $recongps[] = array('recons' => array($recon), 'transfers' => array());
 
+            // ne récupère que les 18 derniers groupements
             $res = XDB::query("SELECT  recongroup_id AS id
                                  FROM  payment_reconcilations
                              GROUP BY  recongroup_id
-                             ORDER BY  MAX(period_end) DESC, MIN(period_start) DESC");
+                             ORDER BY  MAX(period_end) DESC, MIN(period_start) DESC
+                                LIMIT  18");
             foreach ($res->fetchAllAssoc() as $recongp) {
                 $res = XDB::query("SELECT  r.id, short_name AS method, period_start, period_end, status,
                                            payment_count, sum_amounts, sum_commissions
@@ -710,11 +711,26 @@ class PaymentModule extends PLModule
                                   $recongp['id']);
                 $recongp['recons'] = $res->fetchAllAssoc();
 
-                $res = XDB::query('SELECT  id, payment_id, amount, account_id, message, date
-                                     FROM  payment_transfers
+                $res = XDB::query('SELECT  t.id, t.payment_id, t.amount, t.message, t.date
+                                     FROM  payment_transfers    AS t
                                     WHERE  recongroup_id = {?}',
                                   $recongp['id']);
-                $recongp['transfers'] = $res->fetchAllAssoc();
+                $transfers = $res->fetchAllAssoc();
+                foreach ($transfers as $id => $t) {
+                    if ($t['date'] == NULL)  { // si le virement n'est pas fait, on va récupérer le rib associé au paiment
+                        $ownertmp = XDB::fetchOneCell('SELECT  b.owner
+                                                         FROM  payment_bankaccounts AS b
+                                                    LEFT JOIN  payments             AS p ON (p.rib_id = b.id)
+                                                        WHERE  p.id = {?}', $t['payment_id']);
+                    } else { // sinon on prend celui associé au virement
+                        $ownertmp = XDB::fetchOneCell('SELECT  b.owner
+                                                         FROM  payment_bankaccounts AS b
+                                                    LEFT JOIN  payment_transfers    AS t ON (t.account_id = b.id)
+                                                        WHERE  t.id = {?}', $t['id']);
+                    }
+                    $transfers[$id]['owner'] = $ownertmp;
+                }
+                $recongp['transfers'] = $transfers;
 
                 $recongps[] = $recongp;
             }
@@ -722,7 +738,7 @@ class PaymentModule extends PLModule
         }
     }
 
-    function handler_adm_importlogs(&$page, $step, $param = null) {
+    function handler_adm_importlogs($page, $step, $param = null) {
         $page->setTitle('Administration - Paiements - Réconciliations');
         $page->changeTpl('payment/reconcile.tpl');
         $page->assign('step', $step);
@@ -894,7 +910,7 @@ class PaymentModule extends PLModule
         }
     }
 
-    function handler_adm_transfers(&$page, $action = null, $id = null) {
+    function handler_adm_transfers($page, $action = null, $id = null) {
         // list/log all bank transfers and link them to individual transactions
 
         if (Post::has('generate')) {
@@ -918,7 +934,7 @@ class PaymentModule extends PLModule
                                  FROM  payment_transactions AS t
                             LEFT JOIN  payments             AS p ON (t.ref = p.id)
                             LEFT JOIN  groups               AS g ON (p.asso_id = g.id)
-                                WHERE  t.recon_id IN {?}
+                                WHERE  t.recon_id IN {?} AND t.status = "confirmed"
                              GROUP BY  t.ref',
                          $recongp_id, $recon_ids);
 
@@ -941,9 +957,13 @@ class PaymentModule extends PLModule
 
         } elseif ($action == "confirm") {
             S::assert_xsrf_token();
+            $account_id = XDB::fetchOneCell('SELECT  rib_id
+                                               FROM  payments          AS p 
+                                          LEFT JOIN  payment_transfers AS t ON (t.payment_id = p.id)
+                                              WHERE  t.id = {?}', $id);
             XDB::execute('UPDATE  payment_transfers
-                             SET  date = NOW()
-                           WHERE  id = {?}', $id);
+                             SET  date = NOW(), account_id = {?}
+                           WHERE  id = {?}', $account_id, $id);
 
             $page->trigSuccess('Virement ' . $id . ' confirmé.');
             $this->handler_adm_reconcile($page);
@@ -968,7 +988,11 @@ class PaymentLogsImporter extends CSVImporter {
         $this->result = array();
         foreach ($this->data as $line) {
             $a = $this->makeAssoc($line, $insert_relation);
+            // convert date
             $a['date'] = preg_replace('/([0-9]{2})\/([0-9]{2})\/([0-9]{4}).*/', '\3-\2-\1', $a['date']);
+            $a['date'] = preg_replace('/T.*/','', $a['date']);
+
+            // convert money
             $a['amount'] = str_replace(',', '.', $a['amount']);
             $a['commission'] = str_replace(',', '.', $a['commission']);
             $this->result[] = $a;
@@ -981,7 +1005,7 @@ class PaymentLogsImporter extends CSVImporter {
 
     static public function compute_systempay_commission($line, $key, $relation) {
         static $EEE_countries = array(
-            'France', 'Allemagne', 'Autriche', 'Belgique', 'Bulgarie', 'Chypre',
+            'France', 'Allemagne', 'Autriche', 'Belgique', 'Bulgarie', 'Chypre', 'Croatie',
             'Danemark', 'Espagne', 'Estonie', 'Finlande', 'Grèce', 'Hongrie', 'Irlande', 'Islande', 'Italie',
             'Lettonie', 'Liechtenstein', 'Lituanie', 'Luxembourg', 'Malte', 'Norvège', 'Pays-Bas', 'Pologne',
             'Portugal', 'Roumanie', 'Royaume-Uni', 'Slovaquie', 'Slovénie', 'Suède', 'République Tchèque'
@@ -994,7 +1018,7 @@ class PaymentLogsImporter extends CSVImporter {
         if (in_array($line['pays carte'], $EEE_countries)) {
             return -0.20 - round($amount * 0.005, 2);
         } else {
-            return -0.20 - round($amount * 0.005, 2) - 0.76;
+            return -0.20 - round($amount * 0.005, 2) - 0.75;
         }
     }
 
@@ -1003,7 +1027,7 @@ class PaymentLogsImporter extends CSVImporter {
             return null;
         }
         $reference = self::getValue($line, 'reference', $relation['reference']);
-        if (ereg('-([0-9]+)$', $reference, $matches)) {
+        if (preg_match('/-([0-9]+)$/', $reference, $matches)) {
             return $matches[1];
         } else {
             return null;
@@ -1011,5 +1035,5 @@ class PaymentLogsImporter extends CSVImporter {
     }
 }
 
-// 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:
 ?>