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