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