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