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