Fix payment comment decoder
[platal.git] / modules / payment.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2007 Polytechnique.org *
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 */
23 function cb_erreur($text) {
24 $mymail = new PlMailer();
25 $mymail->addTo($globals->money->email);
26 $mymail->setFrom("webmaster@" . $globals->mail->domain);
27 $mymail->setSubject("erreur lors d'un télépaiement (CyberPaiement)");
28 $mymail->setTxtBody("\n\n".var_export($_REQUEST,true));
29 $mymail->send();
30 exit;
31 }
32
33 /* sort en affichant une erreur */
34 function paypal_erreur($text, $send=true)
35 {
36 global $page, $erreur;
37 if ($erreur) return;
38 $erreur = $text;
39 if (!$send) return;
40
41 $mymail = new PlMailer();
42 $mymail->addTo($globals->money->email);
43 $mymail->setFrom("webmaster@" . $globals->mail->domain);
44 $mymail->setSubject("erreur lors d'un télépaiement (PayPal)");
45 $mymail->setTxtBody("\n\n".var_export($_REQUEST,true));
46 $mymail->send();
47
48 $page->trig($text);
49 }
50
51 /* http://fr.wikipedia.org/wiki/Formule_de_Luhn */
52 function luhn($nombre) {
53 $s = strrev($nombre);
54 $sum = 0;
55 for ($i = 0; $i < strlen($s); $i++) {
56 $dgt = $s{$i};
57 $sum += ($i % 2) ? (2*$dgt) % 9 : $dgt;
58 }
59 return $sum % 10;
60 }
61
62 /* calcule la clé d'acceptation a partir de 5 champs */
63 function cle_accept($d1,$d2,$d3,$d4,$d5)
64 {
65 $m1 = luhn($d1.$d5);
66 $m2 = luhn($d2.$d5);
67 $m3 = luhn($d3.$d5);
68 $m4 = luhn($d4.$d5);
69 $n = $m1 + $m2 + $m3 + $m4;
70 $alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
71 return $alpha{$n-1}.$m1.$m2.$m3.$m4;
72 }
73
74 /* decode the comment */
75 function comment_decode($comment) {
76 $comment = urldecode($comment);
77 if (is_utf8($comment)) {
78 return $comment;
79 } else {
80 return utf8_encode($comment);
81 }
82 }
83
84
85 class PaymentModule extends PLModule
86 {
87 function handlers()
88 {
89 return array(
90 'payment' => $this->make_hook('payment', AUTH_MDP),
91 'payment/cyber_return' => $this->make_hook('cyber_return', AUTH_PUBLIC),
92 'payment/paypal_return' => $this->make_hook('paypal_return', AUTH_PUBLIC),
93 '%grp/paiement' => $this->make_hook('xnet_payment', AUTH_MDP),
94 '%grp/payment' => $this->make_hook('xnet_payment', AUTH_MDP),
95 '%grp/payment/cyber_return' => $this->make_hook('cyber_return', AUTH_PUBLIC),
96 '%grp/payment/paypal_return' => $this->make_hook('paypal_return', AUTH_PUBLIC),
97 'admin/payments' => $this->make_hook('admin', AUTH_MDP, 'admin'),
98
99 );
100 }
101
102 function handler_payment(&$page, $ref = -1)
103 {
104 global $globals;
105
106 require_once 'profil.func.inc.php' ;
107 require_once dirname(__FILE__).'/payment/money.inc.php' ;
108
109 if (!empty($GLOBALS['IS_XNET_SITE'])) {
110 if (!$globals->asso('id')) {
111 return PL_NOT_FOUND;
112 }
113 $res = XDB::query("SELECT asso_id
114 FROM paiement.paiements
115 WHERE asso_id = {?} AND id = {?}",
116 $globals->asso('id'), $ref);
117 if (!$res->numRows()) {
118 return PL_FORBIDDEN;
119 }
120 }
121 $page->changeTpl('payment/index.tpl');
122 $page->assign('xorg_title','Polytechnique.org - Télépaiements');
123
124 // initialisation
125 $op = Env::v('op', 'select');
126 $meth = new PayMethod(Env::i('methode', -1));
127 $pay = new Payment($ref);
128
129 if($pay->flags->hasflag('old')){
130 $page->trig("La transaction selectionnée est périmée.");
131 $pay = new Payment();
132 }
133 $val = Env::v('montant') != 0 ? Env::v('montant') : $pay->montant_def;
134
135 if (($e = $pay->check($val)) !== true) {
136 $page->trig($e);
137 }
138
139 if ($op=='submit') {
140 $pay->init($val, $meth);
141 $pay->prepareform($pay);
142 } else {
143 $res = XDB::iterator("SELECT timestamp, montant
144 FROM paiement.transactions
145 WHERE uid = {?} AND ref = {?}
146 ORDER BY timestamp DESC",
147 S::v('uid', -1), $ref);
148
149 if ($res->total()) $page->assign('transactions', $res);
150 }
151
152 $val = floor($val).".".substr(floor(($val - floor($val))*100+100),1);
153 $page->assign('montant',$val);
154 $page->assign('comment',Env::v('comment'));
155
156 $page->assign('meth', $meth);
157 $page->assign('pay', $pay);
158 $page->assign('evtlink', $pay->event());
159
160 $page->assign('prefix', $globals->money->mpay_tprefix);
161 }
162
163 function handler_cyber_return(&$page, $uid = null)
164 {
165 /* reference banque (numero de transaction) */
166 $champ901 = Env::s('CHAMP901');
167 /* cle d'acceptation */
168 $champ905 = Env::s('CHAMP905');
169 /* code retour */
170 $champ906 = Env::s('CHAMP906');
171 /* email renvoye par la banque */
172 $champ104 = Env::s('CHAMP104');
173 /* reference complete de la commande */
174 $champ200 = Env::s('CHAMP200');
175 /* montant de la transaction */
176 $champ201 = Env::s('CHAMP201');
177 /* devise */
178 $champ202 = Env::s('CHAMP202');
179 $montant = "$champ201 $champ202";
180
181 /* on extrait les informations sur l'utilisateur */
182 $res = XDB::query("
183 SELECT a.prenom,a.nom,a.promo,l.alias,FIND_IN_SET('femme', a.flags)
184 FROM auth_user_md5 AS a
185 INNER JOIN aliases AS l ON (a.user_id=l.id AND type!='homonyme')
186 WHERE a.user_id={?}", $uid);
187 if (!list($prenom,$nom,$promo,$forlife,$femme) = $res->fetchOneRow()) {
188 cb_erreur("uid invalide");
189 }
190
191
192 /* on extrait la reference de la commande */
193 if (!ereg('-xorg-([0-9]+)$',$champ200,$matches)) {
194 cb_erreur("référence de commande invalide");
195 }
196
197 echo ($ref = $matches[1]);
198 $res = XDB::query("SELECT mail,text,confirmation
199 FROM paiement.paiements
200 WHERE id={?}", $ref);
201 if (!list($conf_mail,$conf_title,$conf_text) = $res->fetchOneRow()) {
202 cb_erreur("référence de commande inconnue");
203 }
204
205 /* on extrait le code de retour */
206 if ($champ906 != "0000") {
207 $res = XDB::query("SELECT rcb.text,c.id,c.text
208 FROM paiement.codeRCB AS rcb
209 LEFT JOIN paiement.codeC AS c ON rcb.codeC=c.id
210 WHERE rcb.id='$champ906'");
211 if (list($rcb_text, $c_id, $c_text) = $res->fetchOneRow()) {
212 cb_erreur("erreur lors du paiement : $c_text ($c_id)");
213 } else{
214 cb_erreur("erreur inconnue lors du paiement");
215 }
216 }
217
218 /* on fait l'insertion en base de donnees */
219 XDB::execute("INSERT INTO paiement.transactions (id,uid,ref,fullref,montant,cle,comment)
220 VALUES ({?},{?},{?},{?},{?},{?},{?})",
221 $champ901, $uid, $ref, $champ200, $montant, $champ905,Env::v('comment'));
222
223 /* on genere le mail de confirmation */
224 $conf_text = str_replace("<prenom>",$prenom,$conf_text);
225 $conf_text = str_replace("<nom>",$nom,$conf_text);
226 $conf_text = str_replace("<promo>",$promo,$conf_text);
227 $conf_text = str_replace("<montant>",$montant,$conf_text);
228 $conf_text = str_replace("<salutation>",$femme ? "Chère" : "Cher",$conf_text);
229 $conf_text = str_replace("<cher>",$femme ? "Chère" : "Cher",$conf_text);
230
231 $mymail = new PlMailer();
232 $mymail->setFrom($conf_mail);
233 $mymail->addTo("\"$prenom $nom\" <$forlife@" . $globals->mail->domain . '>');
234 $mymail->addCc($conf_mail);
235 $mymail->setSubject($conf_title);
236 $mymail->setWikiBody($conf_text);
237 $mymail->send(S::v('mail_fmt') == 'html');
238
239 /* on envoie les details de la transaction à telepaiement@ */
240 $mymail = new PlMailer();
241 $mymail->setFrom("webmaster@" . $globals->mail->domain);
242 $mymail->addTo($globals->money->email);
243 $mymail->setSubject($conf_title);
244 $msg = "utilisateur : $prenom $nom ($uid)\n".
245 "mail : $forlife@polytechnique.org\n\n".
246 "paiement : $conf_title ($conf_mail)\n".
247 "reference : $champ200\n".
248 "montant : $montant\n\n".
249 "dump de REQUEST:\n".
250 var_export($_REQUEST,true);
251 $mymail->setTxtBody($msg);
252 $mymail->send();
253 exit;
254 }
255
256 function handler_paypal_return(&$page, $uid = null)
257 {
258 $page->changeTpl('payment/retour_paypal.tpl');
259
260 /* reference banque (numero de transaction) */
261 $no_transaction = Env::s('tx');
262 /* token a renvoyer pour avoir plus d'information */
263 $clef = Env::s('sig');
264 /* code retour */
265 $status = Env::s('st');
266 /* raison */
267 $reason = ($status == 'Pending')? Env::s('pending_reason'): Env::s('reason_code');
268 /* reference complete de la commande */
269 $fullref = Env::s('cm');
270 /* montant de la transaction */
271 $montant_nb = Env::s('amt');
272 /* devise */
273 $montant_dev = Env::s('cc');
274 $montant = "$montant_nb $montant_dev";
275
276 /* on extrait le code de retour */
277 if ($status != "Completed") {
278 if ($status)
279 paypal_erreur("erreur lors du paiement : $status - $reason");
280 else
281 paypal_erreur("Paiement annulé", false);
282 }
283
284 /* on extrait les informations sur l'utilisateur */
285 $res = XDB::query("
286 SELECT a.prenom,a.nom,a.promo,l.alias,FIND_IN_SET('femme', a.flags)
287 FROM auth_user_md5 AS a
288 INNER JOIN aliases AS l ON (a.user_id=l.id AND type!='homonyme')
289 WHERE a.user_id={?}", $uid);
290 if (!list($prenom,$nom,$promo,$forlife,$femme) = $res->fetchOneRow()) {
291 paypal_erreur("uid invalide");
292 }
293
294 /* on extrait la reference de la commande */
295 if (!ereg('-xorg-([0-9]+)$',$fullref,$matches)) {
296 paypal_erreur("référence de commande invalide");
297 }
298
299 $ref = $matches[1];
300 $res = XDB::query("SELECT mail,text,confirmation
301 FROM paiement.paiements
302 WHERE id={?}", $ref);
303 if (!list($conf_mail,$conf_title,$conf_text) = $res->fetchOneRow()) {
304 paypal_erreur("référence de commande inconnue");
305 }
306
307 /* on fait l'insertion en base de donnees */
308 XDB::execute("INSERT INTO paiement.transactions (id,uid,ref,fullref,montant,cle,comment)
309 VALUES ({?},{?},{?},{?},{?},{?},{?})",
310 $no_transaction, $uid, $ref, $fullref, $montant, $clef, Env::v('comment'));
311
312 /* on genere le mail de confirmation */
313 $conf_text = str_replace("<prenom>",$prenom,$conf_text);
314 $conf_text = str_replace("<nom>",$nom,$conf_text);
315 $conf_text = str_replace("<promo>",$promo,$conf_text);
316 $conf_text = str_replace("<montant>",$montant,$conf_text);
317 $conf_text = str_replace("<salutation>",$femme ? "Chère" : "Cher",$conf_text);
318 $conf_text = str_replace("<cher>",$femme ? "Chère" : "Cher",$conf_text);
319
320 $mymail = new PlMailer();
321 $mymail->setFrom($conf_mail);
322 $mymail->addTo("\"$prenom $nom\" <$forlife@" . $globals->mail->domain . '>');
323 $mymail->addCc($conf_mail);
324 $mymail->setSubject($conf_title);
325 $mymail->setWikiBody($conf_text);
326 $mymail->send(S::v('mail_fmt') == 'html');
327
328 /* on envoie les details de la transaction à telepaiement@ */
329 $mymail = new PlMailer();
330 $mymail->setFrom("webmaster@" . $globals->mail->domain);
331 $mymail->addTo($globals->money->email);
332 $mymail->setSubject($conf_title);
333 $msg = "utilisateur : $prenom $nom ($uid)\n".
334 "mail : $forlife@polytechnique.org\n\n".
335 "paiement : $conf_title ($conf_mail)\n".
336 "reference : $no_transaction\n".
337 "montant : $montant\n\n".
338 "dump de REQUEST:\n".
339 var_export($_REQUEST,true);
340 $mymail->setTxtBody($msg);
341 $mymail->send();
342
343 $page->assign('texte', $conf_text);
344 $page->assign('erreur', $erreur);
345 }
346
347 function handler_xnet_payment(&$page, $pid = null)
348 {
349 global $globals;
350
351 $perms = S::v('perms');
352 if (!$perms->hasFlag('groupmember')) {
353 if (is_null($pid)) {
354 return PL_FORBIDDEN;
355 }
356 $res = XDB::query("SELECT 1
357 FROM groupex.evenements AS e
358 INNER JOIN groupex.evenements_participants AS ep ON (ep.eid = e.eid AND uid = {?})
359 WHERE e.paiement_id = {?} AND e.asso_id = {?}",
360 S::i('uid'), $pid, $globals->asso('id'));
361 if ($res->numRows() == 0) {
362 return PL_FORBIDDEN;
363 }
364 }
365
366 if (!is_null($pid)) {
367 return $this->handler_payment($page, $pid);
368 }
369 $page->changeTpl('payment/xnet.tpl');
370
371 $res = XDB::query(
372 "SELECT id, text, url
373 FROM {$globals->money->mpay_tprefix}paiements
374 WHERE asso_id = {?} AND NOT FIND_IN_SET('old', flags)
375 ORDER BY id DESC", $globals->asso('id'));
376 $tit = $res->fetchAllAssoc();
377 $page->assign('titres', $tit);
378
379 $order = Env::v('order', 'timestamp');
380 $orders = array('timestamp', 'nom', 'promo', 'montant', 'comment');
381 if (!in_array($order, $orders)) {
382 $order = 'timestamp';
383 } elseif ($order == 'comment') {
384 $order = 't.comment';
385 }
386 $inv_order = Env::v('order_inv', 0);
387 $page->assign('order', $order);
388 $page->assign('order_inv', !$inv_order);
389
390 if ($order == 'timestamp') {
391 $inv_order = !$inv_order;
392 }
393
394 if ($inv_order) {
395 $inv_order = ' DESC';
396 } else {
397 $inv_order = '';
398 }
399 if ($order == 'montant') {
400 $order = 'LENGTH(montant) '.$inv_order.', montant';
401 }
402
403 $orderby = 'ORDER BY '.$order.$inv_order;
404 if ($order != 'nom') {
405 $orderby .= ', nom'; $inv_order = '';
406 }
407 $orderby .= ', prenom'.$inv_order;
408 if ($order != 'timestamp') {
409 $orderby .= ', timestamp DESC';
410 }
411
412 $trans = array();
413 $event = array();
414 foreach($tit as $foo) {
415 $pid = $foo['id'];
416 if (may_update()) {
417 $res = XDB::query("SELECT IF(u.nom_usage<>'', u.nom_usage, u.nom) AS nom,
418 u.prenom, u.promo, a.alias, timestamp AS `date`, t.comment, montant
419 FROM {$globals->money->mpay_tprefix}transactions AS t
420 INNER JOIN auth_user_md5 AS u ON ( t.uid = u.user_id )
421 INNER JOIN aliases AS a ON ( t.uid = a.id AND a.type='a_vie' )
422 WHERE ref = {?} ".$orderby, $pid);
423 $trans[$pid] = $res->fetchAllAssoc();
424 $sum = 0;
425 foreach ($trans[$pid] as $i => $t) {
426 $sum += strtr(substr($t['montant'], 0, strpos($t['montant'], 'EUR')), ',', '.');
427 $trans[$pid][$i]['montant'] = str_replace('EUR', '€', $t['montant']);
428 }
429 $trans[$pid][] = array('nom' => 'somme totale',
430 'montant' => strtr($sum, '.', ',').' €');
431 }
432 $res = XDB::iterRow("SELECT e.eid, e.short_name, e.intitule, ep.nb, ei.montant, ep.paid
433 FROM groupex.evenements AS e
434 LEFT JOIN groupex.evenements_participants AS ep ON (ep.eid = e.eid AND uid = {?})
435 INNER JOIN groupex.evenements_items AS ei ON (ep.eid = ei.eid AND ep.item_id = ei.item_id)
436 WHERE e.paiement_id = {?}",
437 S::v('uid'), $pid);
438 $event[$pid] = array();
439 $event[$pid]['paid'] = 0;
440 if ($res->total()) {
441 $event[$pid]['topay'] = 0;
442 while(list($eid, $shortname, $title, $nb, $montant, $paid) = $res->next()) {
443 $event[$pid]['topay'] += ($nb * $montant);
444 $event[$pid]['eid'] = $eid;
445 $event[$pid]['shortname'] = $shortname;
446 $event[$pid]['title'] = $title;
447 $event[$pid]['ins'] = !is_null($nb);
448 $event[$pid]['paid'] = $paid;
449 }
450 }
451 $res = XDB::query("SELECT montant
452 FROM {$globals->money->mpay_tprefix}transactions AS t
453 WHERE ref = {?} AND uid = {?}", $pid, S::v('uid'));
454 $montants = $res->fetchColumn();
455
456 foreach ($montants as $m) {
457 $p = strtr(substr($m, 0, strpos($m, 'EUR')), ',', '.');
458 $event[$pid]['paid'] += trim($p);
459 }
460 }
461 $page->register_modifier('decode_comment', 'decode_comment');
462 $page->assign('trans', $trans);
463 $page->assign('event', $event);
464 }
465
466 function handler_admin(&$page, $action = 'list', $id = null) {
467 $page->assign('xorg_title','Polytechnique.org - Administration - Paiements');
468 $page->assign('title', 'Gestion des télépaiements');
469 $table_editor = new PLTableEditor('admin/payments','paiement.paiements','id');
470 $table_editor->add_join_table('paiement.transactions','ref',true);
471 $table_editor->add_sort_field('flags');
472 $table_editor->add_sort_field('id', true, true);
473 $table_editor->on_delete("UPDATE paiement.paiements SET flags = 'old' WHERE id = {?}", "Le paiement a été archivé");
474 $table_editor->describe('text','intitulé',true);
475 $table_editor->describe('url','site web',false);
476 $table_editor->describe('montant_def','montant par défaut',false);
477 $table_editor->describe('montant_min','montant minimum',false);
478 $table_editor->describe('montant_max','montant maximum',false);
479 $table_editor->describe('mail','email contact',true);
480 $table_editor->describe('confirmation','message confirmation',false);
481 $table_editor->apply($page, $action, $id);
482 }
483 }
484
485 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
486 ?>