Various bugfixes.
[platal.git] / modules / payment.php
CommitLineData
a2558f2b 1<?php
2/***************************************************************************
8d84c630 3 * Copyright (C) 2003-2009 Polytechnique.org *
a2558f2b 4 * http://opensource.polytechnique.org/ *
5 * *
6 * This program is free software; you can redistribute it and/or modify *
7 * it under the terms of the GNU General Public License as published by *
8 * the Free Software Foundation; either version 2 of the License, or *
9 * (at your option) any later version. *
10 * *
11 * This program is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU General Public License *
17 * along with this program; if not, write to the Free Software *
18 * Foundation, Inc., *
19 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
20 ***************************************************************************/
21
22/* sort en affichant une erreur */
23function cb_erreur($text) {
115c90db 24 global $globals;
1e33266a 25 $mymail = new PlMailer();
d7dd70be 26 $mymail->addTo($globals->money->email);
1d55fe45 27 $mymail->setFrom("webmaster@" . $globals->mail->domain);
a7de4ef7 28 $mymail->setSubject("erreur lors d'un télépaiement (CyberPaiement)");
a2558f2b 29 $mymail->setTxtBody("\n\n".var_export($_REQUEST,true));
30 $mymail->send();
31 exit;
32}
33
34/* sort en affichant une erreur */
88e3843c 35function paypal_erreur($text, $send=true)
36{
d7610c35 37 global $erreur, $globals;
a2558f2b 38 if ($erreur) return;
39 $erreur = $text;
40 if (!$send) return;
41
1e33266a 42 $mymail = new PlMailer();
d7dd70be 43 $mymail->addTo($globals->money->email);
1d55fe45 44 $mymail->setFrom("webmaster@" . $globals->mail->domain);
a7de4ef7 45 $mymail->setSubject("erreur lors d'un télépaiement (PayPal)");
a2558f2b 46 $mymail->setTxtBody("\n\n".var_export($_REQUEST,true));
47 $mymail->send();
48
d7610c35 49 Platal::page()->trigError($text);
a2558f2b 50}
51
52/* http://fr.wikipedia.org/wiki/Formule_de_Luhn */
53function luhn($nombre) {
54 $s = strrev($nombre);
55 $sum = 0;
56 for ($i = 0; $i < strlen($s); $i++) {
57 $dgt = $s{$i};
58 $sum += ($i % 2) ? (2*$dgt) % 9 : $dgt;
59 }
60 return $sum % 10;
61}
62
a7de4ef7 63/* calcule la clé d'acceptation a partir de 5 champs */
a2558f2b 64function cle_accept($d1,$d2,$d3,$d4,$d5)
65{
66 $m1 = luhn($d1.$d5);
67 $m2 = luhn($d2.$d5);
68 $m3 = luhn($d3.$d5);
69 $m4 = luhn($d4.$d5);
70 $n = $m1 + $m2 + $m3 + $m4;
71 $alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
72 return $alpha{$n-1}.$m1.$m2.$m3.$m4;
73}
74
17793ccf
FB
75/* decode the comment */
76function comment_decode($comment) {
77 $comment = urldecode($comment);
78 if (is_utf8($comment)) {
79 return $comment;
80 } else {
81 return utf8_encode($comment);
82 }
83}
84
a2558f2b 85
86class PaymentModule extends PLModule
87{
88 function handlers()
89 {
90 return array(
eb5a266d
SJ
91 'payment' => $this->make_hook('payment', AUTH_MDP),
92 'payment/cyber_return' => $this->make_hook('cyber_return', AUTH_PUBLIC, 'user', NO_HTTPS),
93 'payment/paypal_return' => $this->make_hook('paypal_return', AUTH_PUBLIC, 'user', NO_HTTPS),
94 '%grp/paiement' => $this->make_hook('xnet_payment', AUTH_MDP),
95 '%grp/payment' => $this->make_hook('xnet_payment', AUTH_MDP),
96 '%grp/payment/cyber_return' => $this->make_hook('cyber_return', AUTH_PUBLIC, 'user', NO_HTTPS),
41cce805 97 '%grp/payment/paypal_return' => $this->make_hook('paypal_return', AUTH_PUBLIC, 'user', NO_HTTPS),
eb5a266d 98 'admin/payments' => $this->make_hook('admin', AUTH_MDP, 'admin'),
eaf30d86 99
a2558f2b 100 );
101 }
102
103 function handler_payment(&$page, $ref = -1)
104 {
105 global $globals;
106
107 require_once 'profil.func.inc.php' ;
460d8f55 108 $this->load('money.inc.php');
a2558f2b 109
98a7e9dc 110 if (!empty($GLOBALS['IS_XNET_SITE'])) {
111 if (!$globals->asso('id')) {
112 return PL_NOT_FOUND;
113 }
114 $res = XDB::query("SELECT asso_id
115 FROM paiement.paiements
116 WHERE asso_id = {?} AND id = {?}",
117 $globals->asso('id'), $ref);
118 if (!$res->numRows()) {
119 return PL_FORBIDDEN;
120 }
98a7e9dc 121 }
1490093c 122 $page->changeTpl('payment/index.tpl');
46f272fe 123 $page->setTitle('Télépaiements');
a2558f2b 124
125 // initialisation
5e2307dc 126 $op = Env::v('op', 'select');
127 $meth = new PayMethod(Env::i('methode', -1));
a2558f2b 128 $pay = new Payment($ref);
129
130 if($pay->flags->hasflag('old')){
a7d35093 131 $page->trigError("La transaction selectionnée est périmée.");
a2558f2b 132 $pay = new Payment();
133 }
5e2307dc 134 $val = Env::v('montant') != 0 ? Env::v('montant') : $pay->montant_def;
a2558f2b 135
136 if (($e = $pay->check($val)) !== true) {
a7d35093 137 $page->trigError($e);
a2558f2b 138 }
139
140 if ($op=='submit') {
141 $pay->init($val, $meth);
142 $pay->prepareform($pay);
143 } else {
08cce2ff 144 $res = XDB::iterator("SELECT timestamp, montant
8a7fab54 145 FROM paiement.transactions
146 WHERE uid = {?} AND ref = {?}
147 ORDER BY timestamp DESC",
148 S::v('uid', -1), $ref);
a2558f2b 149
150 if ($res->total()) $page->assign('transactions', $res);
151 }
152
153 $val = floor($val).".".substr(floor(($val - floor($val))*100+100),1);
154 $page->assign('montant',$val);
bff6d838 155 $page->assign('comment',Env::v('comment'));
a2558f2b 156
157 $page->assign('meth', $meth);
158 $page->assign('pay', $pay);
159 $page->assign('evtlink', $pay->event());
160
a3a049fc 161 $page->assign('prefix', $globals->money->mpay_tprefix);
a2558f2b 162 }
163
164 function handler_cyber_return(&$page, $uid = null)
165 {
a2558f2b 166 /* reference banque (numero de transaction) */
7280eb45 167 $champ901 = Env::s('CHAMP901');
a2558f2b 168 /* cle d'acceptation */
7280eb45 169 $champ905 = Env::s('CHAMP905');
a2558f2b 170 /* code retour */
7280eb45 171 $champ906 = Env::s('CHAMP906');
a2558f2b 172 /* email renvoye par la banque */
7280eb45 173 $champ104 = Env::s('CHAMP104');
a2558f2b 174 /* reference complete de la commande */
7280eb45 175 $champ200 = Env::s('CHAMP200');
a2558f2b 176 /* montant de la transaction */
7280eb45 177 $champ201 = Env::s('CHAMP201');
a2558f2b 178 /* devise */
7280eb45 179 $champ202 = Env::s('CHAMP202');
a2558f2b 180 $montant = "$champ201 $champ202";
181
182 /* on extrait les informations sur l'utilisateur */
1eaaa62d
FB
183 $user = User::get($uid);
184 if (!$user) {
a2558f2b 185 cb_erreur("uid invalide");
186 }
187
188
189 /* on extrait la reference de la commande */
1eaaa62d 190 if (!ereg('-xorg-([0-9]+)$', $champ200, $matches)) {
a7de4ef7 191 cb_erreur("référence de commande invalide");
a2558f2b 192 }
193
194 echo ($ref = $matches[1]);
1eaaa62d 195 $res = XDB::query("SELECT mail, text, confirmation
98a7e9dc 196 FROM paiement.paiements
197 WHERE id={?}", $ref);
1eaaa62d 198 if (!list($conf_mail, $conf_title, $conf_text) = $res->fetchOneRow()) {
a7de4ef7 199 cb_erreur("référence de commande inconnue");
a2558f2b 200 }
201
202 /* on extrait le code de retour */
203 if ($champ906 != "0000") {
1eaaa62d 204 $res = XDB::query('SELECT rcb.text, c.id, c.text
98a7e9dc 205 FROM paiement.codeRCB AS rcb
1eaaa62d
FB
206 LEFT JOIN paiement.codeC AS c ON (rcb.codeC = c.id)
207 WHERE rcb.id = {?}', $champ906);
a2558f2b 208 if (list($rcb_text, $c_id, $c_text) = $res->fetchOneRow()) {
209 cb_erreur("erreur lors du paiement : $c_text ($c_id)");
eaf30d86 210 } else{
a2558f2b 211 cb_erreur("erreur inconnue lors du paiement");
212 }
213 }
214
215 /* on fait l'insertion en base de donnees */
1eaaa62d
FB
216 XDB::execute("INSERT INTO paiement.transactions (id, uid, ref, fullref, montant, cle, comment)
217 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?})",
218 $champ901, $user->id(), $ref, $champ200, $montant, $champ905, Env::v('comment'));
a2558f2b 219
220 /* on genere le mail de confirmation */
d1e61677
SJ
221 $conf_text = str_replace(
222 array('<prenom>', '<nom>', '<promo>', '<montant>', '<salutation>', '<cher>', 'comment>'),
223 array($user->firstName(), $user->lastName(), $user->promo(), $montant,
224 $user->isFemale() ? 'Chère' : 'Cher', $user->isFemale() ? 'Chère' : 'Cher',
225 Env::v('comment')), $conf_text);
a2558f2b 226
7895f3c1 227 global $globals;
1e33266a 228 $mymail = new PlMailer();
a2558f2b 229 $mymail->setFrom($conf_mail);
a2558f2b 230 $mymail->addCc($conf_mail);
231 $mymail->setSubject($conf_title);
88e3843c 232 $mymail->setWikiBody($conf_text);
1eaaa62d 233 $mymail->sendTo($user);
a2558f2b 234
a7de4ef7 235 /* on envoie les details de la transaction à telepaiement@ */
1e33266a 236 $mymail = new PlMailer();
1d55fe45 237 $mymail->setFrom("webmaster@" . $globals->mail->domain);
d7dd70be 238 $mymail->addTo($globals->money->email);
a2558f2b 239 $mymail->setSubject($conf_title);
1eaaa62d
FB
240 $msg = 'utilisateur : ' . $user->login() . ' (' . $user->id() . ')' . "\n" .
241 'mail : ' . $user->forlifeEmail() . "\n\n" .
a2558f2b 242 "paiement : $conf_title ($conf_mail)\n".
243 "reference : $champ200\n".
244 "montant : $montant\n\n".
245 "dump de REQUEST:\n".
246 var_export($_REQUEST,true);
247 $mymail->setTxtBody($msg);
248 $mymail->send();
249 exit;
250 }
251
252 function handler_paypal_return(&$page, $uid = null)
253 {
da157660 254 $page->changeTpl('payment/retour_paypal.tpl');
a2558f2b 255
256 /* reference banque (numero de transaction) */
7280eb45 257 $no_transaction = Env::s('tx');
a2558f2b 258 /* token a renvoyer pour avoir plus d'information */
7280eb45 259 $clef = Env::s('sig');
a2558f2b 260 /* code retour */
7280eb45 261 $status = Env::s('st');
a2558f2b 262 /* raison */
7280eb45 263 $reason = ($status == 'Pending')? Env::s('pending_reason'): Env::s('reason_code');
a2558f2b 264 /* reference complete de la commande */
7280eb45 265 $fullref = Env::s('cm');
a2558f2b 266 /* montant de la transaction */
7280eb45 267 $montant_nb = Env::s('amt');
a2558f2b 268 /* devise */
7280eb45 269 $montant_dev = Env::s('cc');
a2558f2b 270 $montant = "$montant_nb $montant_dev";
271
272 /* on extrait le code de retour */
273 if ($status != "Completed") {
274 if ($status)
275 paypal_erreur("erreur lors du paiement : $status - $reason");
276 else
a7de4ef7 277 paypal_erreur("Paiement annulé", false);
a2558f2b 278 }
279
280 /* on extrait les informations sur l'utilisateur */
1eaaa62d
FB
281 $user = User::get($uid);
282 if (!$user) {
a2558f2b 283 paypal_erreur("uid invalide");
284 }
285
286 /* on extrait la reference de la commande */
1eaaa62d 287 if (!ereg('-xorg-([0-9]+)$', $fullref, $matches)) {
a7de4ef7 288 paypal_erreur("référence de commande invalide");
a2558f2b 289 }
290
291 $ref = $matches[1];
1eaaa62d 292 $res = XDB::query("SELECT mail, text, confirmation
98a7e9dc 293 FROM paiement.paiements
1eaaa62d 294 WHERE id = {?}", $ref);
a2558f2b 295 if (!list($conf_mail,$conf_title,$conf_text) = $res->fetchOneRow()) {
a7de4ef7 296 paypal_erreur("référence de commande inconnue");
a2558f2b 297 }
298
299 /* on fait l'insertion en base de donnees */
1eaaa62d
FB
300 XDB::execute("INSERT INTO paiement.transactions (id, uid, ref, fullref, montant, cle, comment)
301 VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?})",
302 $no_transaction, $user->id(), $ref, $fullref, $montant, $clef, Env::v('comment'));
a2558f2b 303
304 /* on genere le mail de confirmation */
1eaaa62d
FB
305 $conf_text = str_replace(array('<prenom>', '<nom>', '<promo>', '<montant>', '<salutation>', '<cher>'),
306 array($user->firstName(), $user->lastName(), $user->promo(), $montant,
307 $user->isFemale() ? 'Chère' : 'Cher',
308 $user->isFemale() ? 'Chère' : 'Cher'), $conf_text);
a2558f2b 309
7895f3c1 310 global $globals;
1e33266a 311 $mymail = new PlMailer();
a2558f2b 312 $mymail->setFrom($conf_mail);
a2558f2b 313 $mymail->addCc($conf_mail);
314 $mymail->setSubject($conf_title);
88e3843c 315 $mymail->setWikiBody($conf_text);
1eaaa62d 316 $mymail->sendTo($user);
a2558f2b 317
a7de4ef7 318 /* on envoie les details de la transaction à telepaiement@ */
1e33266a 319 $mymail = new PlMailer();
1d55fe45 320 $mymail->setFrom("webmaster@" . $globals->mail->domain);
d7dd70be 321 $mymail->addTo($globals->money->email);
a2558f2b 322 $mymail->setSubject($conf_title);
1eaaa62d
FB
323 $msg = 'utilisateur : ' . $user->login() . ' (' . $user->id() . ')' . "\n" .
324 'mail : ' . $user->forlifeEmail() . "\n\n" .
a2558f2b 325 "paiement : $conf_title ($conf_mail)\n".
1eaaa62d 326 "reference : $champ200\n".
a2558f2b 327 "montant : $montant\n\n".
328 "dump de REQUEST:\n".
329 var_export($_REQUEST,true);
330 $mymail->setTxtBody($msg);
331 $mymail->send();
332
333 $page->assign('texte', $conf_text);
334 $page->assign('erreur', $erreur);
a2558f2b 335 }
98a7e9dc 336
337 function handler_xnet_payment(&$page, $pid = null)
338 {
339 global $globals;
eaf30d86 340
45a5307b
FB
341 $perms = S::v('perms');
342 if (!$perms->hasFlag('groupmember')) {
343 if (is_null($pid)) {
344 return PL_FORBIDDEN;
345 }
346 $res = XDB::query("SELECT 1
347 FROM groupex.evenements AS e
348 INNER JOIN groupex.evenements_participants AS ep ON (ep.eid = e.eid AND uid = {?})
349 WHERE e.paiement_id = {?} AND e.asso_id = {?}",
350 S::i('uid'), $pid, $globals->asso('id'));
351 if ($res->numRows() == 0) {
352 return PL_FORBIDDEN;
353 }
354 }
355
98a7e9dc 356 if (!is_null($pid)) {
357 return $this->handler_payment($page, $pid);
358 }
1490093c 359 $page->changeTpl('payment/xnet.tpl');
eaf30d86 360
98a7e9dc 361 $res = XDB::query(
362 "SELECT id, text, url
363 FROM {$globals->money->mpay_tprefix}paiements
010268b2 364 WHERE asso_id = {?} AND NOT FIND_IN_SET('old', flags)
98a7e9dc 365 ORDER BY id DESC", $globals->asso('id'));
366 $tit = $res->fetchAllAssoc();
367 $page->assign('titres', $tit);
368
98a7e9dc 369
1eaaa62d 370 // TODO: replug sort.
98a7e9dc 371 $trans = array();
372 $event = array();
373 foreach($tit as $foo) {
374 $pid = $foo['id'];
375 if (may_update()) {
1eaaa62d
FB
376 $res = XDB::query('SELECT t.uid, timestamp AS `date`, t.comment, montant
377 FROM ' . $globals->money->mpay_tprefix . 'transactions AS t
378 WHERE t.ref = {?}', $pid);
379 $trans[$pid] = User::getBulkUsersWithUIDs($res->fetchAllAssoc(), 'uid', 'user');
380 $sum = 0;
381 foreach ($trans[$pid] as $i => $t) {
382 $sum += strtr(substr($t['montant'], 0, strpos($t['montant'], 'EUR')), ',', '.');
383 $trans[$pid][$i]['montant'] = str_replace('EUR', '€', $t['montant']);
384 }
385 $trans[$pid][] = array('nom' => 'somme totale',
386 'montant' => strtr($sum, '.', ',').' €');
98a7e9dc 387 }
388 $res = XDB::iterRow("SELECT e.eid, e.short_name, e.intitule, ep.nb, ei.montant, ep.paid
389 FROM groupex.evenements AS e
390 LEFT JOIN groupex.evenements_participants AS ep ON (ep.eid = e.eid AND uid = {?})
391 INNER JOIN groupex.evenements_items AS ei ON (ep.eid = ei.eid AND ep.item_id = ei.item_id)
392 WHERE e.paiement_id = {?}",
393 S::v('uid'), $pid);
394 $event[$pid] = array();
395 $event[$pid]['paid'] = 0;
396 if ($res->total()) {
397 $event[$pid]['topay'] = 0;
398 while(list($eid, $shortname, $title, $nb, $montant, $paid) = $res->next()) {
399 $event[$pid]['topay'] += ($nb * $montant);
400 $event[$pid]['eid'] = $eid;
401 $event[$pid]['shortname'] = $shortname;
402 $event[$pid]['title'] = $title;
403 $event[$pid]['ins'] = !is_null($nb);
404 $event[$pid]['paid'] = $paid;
405 }
406 }
407 $res = XDB::query("SELECT montant
408 FROM {$globals->money->mpay_tprefix}transactions AS t
409 WHERE ref = {?} AND uid = {?}", $pid, S::v('uid'));
410 $montants = $res->fetchColumn();
411
412 foreach ($montants as $m) {
413 $p = strtr(substr($m, 0, strpos($m, 'EUR')), ',', '.');
414 $event[$pid]['paid'] += trim($p);
415 }
416 }
17793ccf 417 $page->register_modifier('decode_comment', 'decode_comment');
98a7e9dc 418 $page->assign('trans', $trans);
419 $page->assign('event', $event);
420 }
eaf30d86 421
92423144 422 function handler_admin(&$page, $action = 'list', $id = null) {
46f272fe 423 $page->setTitle('Administration - Paiements');
a7de4ef7 424 $page->assign('title', 'Gestion des télépaiements');
92423144 425 $table_editor = new PLTableEditor('admin/payments','paiement.paiements','id');
426 $table_editor->add_join_table('paiement.transactions','ref',true);
2e7b5921 427 $table_editor->add_sort_field('flags');
de61dbcf 428 $table_editor->add_sort_field('id', true, true);
a7de4ef7 429 $table_editor->on_delete("UPDATE paiement.paiements SET flags = 'old' WHERE id = {?}", "Le paiement a été archivé");
430 $table_editor->describe('text','intitulé',true);
92423144 431 $table_editor->describe('url','site web',false);
a7de4ef7 432 $table_editor->describe('montant_def','montant par défaut',false);
92423144 433 $table_editor->describe('montant_min','montant minimum',false);
434 $table_editor->describe('montant_max','montant maximum',false);
435 $table_editor->describe('mail','email contact',true);
436 $table_editor->describe('confirmation','message confirmation',false);
437 $table_editor->apply($page, $action, $id);
eaf30d86 438 }
a2558f2b 439}
440
a7de4ef7 441// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
a2558f2b 442?>