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