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