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