Add a generic hash capability to the newsletter.
[platal.git] / modules / payment.php
CommitLineData
a2558f2b 1<?php
2/***************************************************************************
179afa7f 3 * Copyright (C) 2003-2008 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
7895f3c1 231 global $globals;
1e33266a 232 $mymail = new PlMailer();
a2558f2b 233 $mymail->setFrom($conf_mail);
1d55fe45 234 $mymail->addTo("\"$prenom $nom\" <$forlife@" . $globals->mail->domain . '>');
a2558f2b 235 $mymail->addCc($conf_mail);
236 $mymail->setSubject($conf_title);
88e3843c 237 $mymail->setWikiBody($conf_text);
238 $mymail->send(S::v('mail_fmt') == 'html');
a2558f2b 239
a7de4ef7 240 /* on envoie les details de la transaction à telepaiement@ */
1e33266a 241 $mymail = new PlMailer();
1d55fe45 242 $mymail->setFrom("webmaster@" . $globals->mail->domain);
d7dd70be 243 $mymail->addTo($globals->money->email);
a2558f2b 244 $mymail->setSubject($conf_title);
245 $msg = "utilisateur : $prenom $nom ($uid)\n".
246 "mail : $forlife@polytechnique.org\n\n".
247 "paiement : $conf_title ($conf_mail)\n".
248 "reference : $champ200\n".
249 "montant : $montant\n\n".
250 "dump de REQUEST:\n".
251 var_export($_REQUEST,true);
252 $mymail->setTxtBody($msg);
253 $mymail->send();
254 exit;
255 }
256
257 function handler_paypal_return(&$page, $uid = null)
258 {
da157660 259 $page->changeTpl('payment/retour_paypal.tpl');
a2558f2b 260
261 /* reference banque (numero de transaction) */
7280eb45 262 $no_transaction = Env::s('tx');
a2558f2b 263 /* token a renvoyer pour avoir plus d'information */
7280eb45 264 $clef = Env::s('sig');
a2558f2b 265 /* code retour */
7280eb45 266 $status = Env::s('st');
a2558f2b 267 /* raison */
7280eb45 268 $reason = ($status == 'Pending')? Env::s('pending_reason'): Env::s('reason_code');
a2558f2b 269 /* reference complete de la commande */
7280eb45 270 $fullref = Env::s('cm');
a2558f2b 271 /* montant de la transaction */
7280eb45 272 $montant_nb = Env::s('amt');
a2558f2b 273 /* devise */
7280eb45 274 $montant_dev = Env::s('cc');
a2558f2b 275 $montant = "$montant_nb $montant_dev";
276
277 /* on extrait le code de retour */
278 if ($status != "Completed") {
279 if ($status)
280 paypal_erreur("erreur lors du paiement : $status - $reason");
281 else
a7de4ef7 282 paypal_erreur("Paiement annulé", false);
a2558f2b 283 }
284
285 /* on extrait les informations sur l'utilisateur */
08cce2ff 286 $res = XDB::query("
010268b2 287 SELECT a.prenom,a.nom,a.promo,l.alias,FIND_IN_SET('femme', a.flags)
a2558f2b 288 FROM auth_user_md5 AS a
289 INNER JOIN aliases AS l ON (a.user_id=l.id AND type!='homonyme')
290 WHERE a.user_id={?}", $uid);
291 if (!list($prenom,$nom,$promo,$forlife,$femme) = $res->fetchOneRow()) {
292 paypal_erreur("uid invalide");
293 }
294
295 /* on extrait la reference de la commande */
296 if (!ereg('-xorg-([0-9]+)$',$fullref,$matches)) {
a7de4ef7 297 paypal_erreur("référence de commande invalide");
a2558f2b 298 }
299
300 $ref = $matches[1];
08cce2ff 301 $res = XDB::query("SELECT mail,text,confirmation
98a7e9dc 302 FROM paiement.paiements
303 WHERE id={?}", $ref);
a2558f2b 304 if (!list($conf_mail,$conf_title,$conf_text) = $res->fetchOneRow()) {
a7de4ef7 305 paypal_erreur("référence de commande inconnue");
a2558f2b 306 }
307
308 /* on fait l'insertion en base de donnees */
bff6d838 309 XDB::execute("INSERT INTO paiement.transactions (id,uid,ref,fullref,montant,cle,comment)
98a7e9dc 310 VALUES ({?},{?},{?},{?},{?},{?},{?})",
311 $no_transaction, $uid, $ref, $fullref, $montant, $clef, Env::v('comment'));
a2558f2b 312
313 /* on genere le mail de confirmation */
314 $conf_text = str_replace("<prenom>",$prenom,$conf_text);
315 $conf_text = str_replace("<nom>",$nom,$conf_text);
316 $conf_text = str_replace("<promo>",$promo,$conf_text);
317 $conf_text = str_replace("<montant>",$montant,$conf_text);
a7de4ef7 318 $conf_text = str_replace("<salutation>",$femme ? "Chère" : "Cher",$conf_text);
319 $conf_text = str_replace("<cher>",$femme ? "Chère" : "Cher",$conf_text);
a2558f2b 320
7895f3c1 321 global $globals;
1e33266a 322 $mymail = new PlMailer();
a2558f2b 323 $mymail->setFrom($conf_mail);
1d55fe45 324 $mymail->addTo("\"$prenom $nom\" <$forlife@" . $globals->mail->domain . '>');
a2558f2b 325 $mymail->addCc($conf_mail);
326 $mymail->setSubject($conf_title);
88e3843c 327 $mymail->setWikiBody($conf_text);
328 $mymail->send(S::v('mail_fmt') == 'html');
a2558f2b 329
a7de4ef7 330 /* on envoie les details de la transaction à telepaiement@ */
1e33266a 331 $mymail = new PlMailer();
1d55fe45 332 $mymail->setFrom("webmaster@" . $globals->mail->domain);
d7dd70be 333 $mymail->addTo($globals->money->email);
a2558f2b 334 $mymail->setSubject($conf_title);
335 $msg = "utilisateur : $prenom $nom ($uid)\n".
336 "mail : $forlife@polytechnique.org\n\n".
337 "paiement : $conf_title ($conf_mail)\n".
338 "reference : $no_transaction\n".
339 "montant : $montant\n\n".
340 "dump de REQUEST:\n".
341 var_export($_REQUEST,true);
342 $mymail->setTxtBody($msg);
343 $mymail->send();
344
345 $page->assign('texte', $conf_text);
346 $page->assign('erreur', $erreur);
a2558f2b 347 }
98a7e9dc 348
349 function handler_xnet_payment(&$page, $pid = null)
350 {
351 global $globals;
eaf30d86 352
45a5307b
FB
353 $perms = S::v('perms');
354 if (!$perms->hasFlag('groupmember')) {
355 if (is_null($pid)) {
356 return PL_FORBIDDEN;
357 }
358 $res = XDB::query("SELECT 1
359 FROM groupex.evenements AS e
360 INNER JOIN groupex.evenements_participants AS ep ON (ep.eid = e.eid AND uid = {?})
361 WHERE e.paiement_id = {?} AND e.asso_id = {?}",
362 S::i('uid'), $pid, $globals->asso('id'));
363 if ($res->numRows() == 0) {
364 return PL_FORBIDDEN;
365 }
366 }
367
98a7e9dc 368 if (!is_null($pid)) {
369 return $this->handler_payment($page, $pid);
370 }
1490093c 371 $page->changeTpl('payment/xnet.tpl');
eaf30d86 372
98a7e9dc 373 $res = XDB::query(
374 "SELECT id, text, url
375 FROM {$globals->money->mpay_tprefix}paiements
010268b2 376 WHERE asso_id = {?} AND NOT FIND_IN_SET('old', flags)
98a7e9dc 377 ORDER BY id DESC", $globals->asso('id'));
378 $tit = $res->fetchAllAssoc();
379 $page->assign('titres', $tit);
380
381 $order = Env::v('order', 'timestamp');
de4b22cc 382 $orders = array('timestamp', 'nom', 'promo', 'montant', 'comment');
98a7e9dc 383 if (!in_array($order, $orders)) {
384 $order = 'timestamp';
de4b22cc 385 } elseif ($order == 'comment') {
386 $order = 't.comment';
98a7e9dc 387 }
388 $inv_order = Env::v('order_inv', 0);
389 $page->assign('order', $order);
390 $page->assign('order_inv', !$inv_order);
391
392 if ($order == 'timestamp') {
393 $inv_order = !$inv_order;
394 }
395
396 if ($inv_order) {
397 $inv_order = ' DESC';
398 } else {
399 $inv_order = '';
400 }
401 if ($order == 'montant') {
402 $order = 'LENGTH(montant) '.$inv_order.', montant';
403 }
404
405 $orderby = 'ORDER BY '.$order.$inv_order;
406 if ($order != 'nom') {
407 $orderby .= ', nom'; $inv_order = '';
408 }
409 $orderby .= ', prenom'.$inv_order;
410 if ($order != 'timestamp') {
411 $orderby .= ', timestamp DESC';
412 }
413
414 $trans = array();
415 $event = array();
416 foreach($tit as $foo) {
417 $pid = $foo['id'];
418 if (may_update()) {
419 $res = XDB::query("SELECT IF(u.nom_usage<>'', u.nom_usage, u.nom) AS nom,
de4b22cc 420 u.prenom, u.promo, a.alias, timestamp AS `date`, t.comment, montant
98a7e9dc 421 FROM {$globals->money->mpay_tprefix}transactions AS t
422 INNER JOIN auth_user_md5 AS u ON ( t.uid = u.user_id )
423 INNER JOIN aliases AS a ON ( t.uid = a.id AND a.type='a_vie' )
424 WHERE ref = {?} ".$orderby, $pid);
425 $trans[$pid] = $res->fetchAllAssoc();
426 $sum = 0;
427 foreach ($trans[$pid] as $i => $t) {
428 $sum += strtr(substr($t['montant'], 0, strpos($t['montant'], 'EUR')), ',', '.');
a7de4ef7 429 $trans[$pid][$i]['montant'] = str_replace('EUR', '€', $t['montant']);
98a7e9dc 430 }
431 $trans[$pid][] = array('nom' => 'somme totale',
a7de4ef7 432 'montant' => strtr($sum, '.', ',').' €');
98a7e9dc 433 }
434 $res = XDB::iterRow("SELECT e.eid, e.short_name, e.intitule, ep.nb, ei.montant, ep.paid
435 FROM groupex.evenements AS e
436 LEFT JOIN groupex.evenements_participants AS ep ON (ep.eid = e.eid AND uid = {?})
437 INNER JOIN groupex.evenements_items AS ei ON (ep.eid = ei.eid AND ep.item_id = ei.item_id)
438 WHERE e.paiement_id = {?}",
439 S::v('uid'), $pid);
440 $event[$pid] = array();
441 $event[$pid]['paid'] = 0;
442 if ($res->total()) {
443 $event[$pid]['topay'] = 0;
444 while(list($eid, $shortname, $title, $nb, $montant, $paid) = $res->next()) {
445 $event[$pid]['topay'] += ($nb * $montant);
446 $event[$pid]['eid'] = $eid;
447 $event[$pid]['shortname'] = $shortname;
448 $event[$pid]['title'] = $title;
449 $event[$pid]['ins'] = !is_null($nb);
450 $event[$pid]['paid'] = $paid;
451 }
452 }
453 $res = XDB::query("SELECT montant
454 FROM {$globals->money->mpay_tprefix}transactions AS t
455 WHERE ref = {?} AND uid = {?}", $pid, S::v('uid'));
456 $montants = $res->fetchColumn();
457
458 foreach ($montants as $m) {
459 $p = strtr(substr($m, 0, strpos($m, 'EUR')), ',', '.');
460 $event[$pid]['paid'] += trim($p);
461 }
462 }
17793ccf 463 $page->register_modifier('decode_comment', 'decode_comment');
98a7e9dc 464 $page->assign('trans', $trans);
465 $page->assign('event', $event);
466 }
eaf30d86 467
92423144 468 function handler_admin(&$page, $action = 'list', $id = null) {
92423144 469 $page->assign('xorg_title','Polytechnique.org - Administration - Paiements');
a7de4ef7 470 $page->assign('title', 'Gestion des télépaiements');
92423144 471 $table_editor = new PLTableEditor('admin/payments','paiement.paiements','id');
472 $table_editor->add_join_table('paiement.transactions','ref',true);
2e7b5921 473 $table_editor->add_sort_field('flags');
de61dbcf 474 $table_editor->add_sort_field('id', true, true);
a7de4ef7 475 $table_editor->on_delete("UPDATE paiement.paiements SET flags = 'old' WHERE id = {?}", "Le paiement a été archivé");
476 $table_editor->describe('text','intitulé',true);
92423144 477 $table_editor->describe('url','site web',false);
a7de4ef7 478 $table_editor->describe('montant_def','montant par défaut',false);
92423144 479 $table_editor->describe('montant_min','montant minimum',false);
480 $table_editor->describe('montant_max','montant maximum',false);
481 $table_editor->describe('mail','email contact',true);
482 $table_editor->describe('confirmation','message confirmation',false);
483 $table_editor->apply($page, $action, $id);
eaf30d86 484 }
a2558f2b 485}
486
a7de4ef7 487// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
a2558f2b 488?>