Table editor fills the new entry form with the default values of the fields
[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 HermesMailer();
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 HermesMailer();
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 require_once 'diogenes/diogenes.hermes.inc.php';
157
158 /* reference banque (numero de transaction) */
159 $champ901 = clean_request('CHAMP901');
160 /* cle d'acceptation */
161 $champ905 = clean_request('CHAMP905');
162 /* code retour */
163 $champ906 = clean_request('CHAMP906');
164 /* email renvoye par la banque */
165 $champ104 = clean_request('CHAMP104');
166 /* reference complete de la commande */
167 $champ200 = clean_request('CHAMP200');
168 /* montant de la transaction */
169 $champ201 = clean_request('CHAMP201');
170 /* devise */
171 $champ202 = clean_request('CHAMP202');
172 $montant = "$champ201 $champ202";
173
174 /* on extrait les informations sur l'utilisateur */
175 $res = XDB::query("
176 SELECT a.prenom,a.nom,a.promo,l.alias,FIND_IN_SET(a.flags,'femme')
177 FROM auth_user_md5 AS a
178 INNER JOIN aliases AS l ON (a.user_id=l.id AND type!='homonyme')
179 WHERE a.user_id={?}", $uid);
180 if (!list($prenom,$nom,$promo,$forlife,$femme) = $res->fetchOneRow()) {
181 cb_erreur("uid invalide");
182 }
183
184
185 /* on extrait la reference de la commande */
186 if (!ereg('-xorg-([0-9]+)$',$champ200,$matches)) {
187 cb_erreur("référence de commande invalide");
188 }
189
190 echo ($ref = $matches[1]);
191 $res = XDB::query("SELECT mail,text,confirmation
192 FROM paiement.paiements
193 WHERE id={?}", $ref);
194 if (!list($conf_mail,$conf_title,$conf_text) = $res->fetchOneRow()) {
195 cb_erreur("référence de commande inconnue");
196 }
197
198 /* on extrait le code de retour */
199 if ($champ906 != "0000") {
200 $res = XDB::query("SELECT rcb.text,c.id,c.text
201 FROM paiement.codeRCB AS rcb
202 LEFT JOIN paiement.codeC AS c ON rcb.codeC=c.id
203 WHERE rcb.id='$champ906'");
204 if (list($rcb_text, $c_id, $c_text) = $res->fetchOneRow()) {
205 cb_erreur("erreur lors du paiement : $c_text ($c_id)");
206 } else{
207 cb_erreur("erreur inconnue lors du paiement");
208 }
209 }
210
211 /* on fait l'insertion en base de donnees */
212 XDB::execute("INSERT INTO paiement.transactions (id,uid,ref,fullref,montant,cle,comment)
213 VALUES ({?},{?},{?},{?},{?},{?},{?})",
214 $champ901, $uid, $ref, $champ200, $montant, $champ905,Env::v('comment'));
215
216 /* on genere le mail de confirmation */
217 $conf_text = str_replace("<prenom>",$prenom,$conf_text);
218 $conf_text = str_replace("<nom>",$nom,$conf_text);
219 $conf_text = str_replace("<promo>",$promo,$conf_text);
220 $conf_text = str_replace("<montant>",$montant,$conf_text);
221 $conf_text = str_replace("<salutation>",$femme ? "Chère" : "Cher",$conf_text);
222 $conf_text = str_replace("<cher>",$femme ? "Chère" : "Cher",$conf_text);
223
224 $mymail = new HermesMailer();
225 $mymail->setFrom($conf_mail);
226 $mymail->addTo("\"$prenom $nom\" <$forlife@polytechnique.org>");
227 $mymail->addCc($conf_mail);
228 $mymail->setSubject($conf_title);
229 $mymail->setTxtBody($conf_text);
230 $mymail->send();
231
232 /* on envoie les details de la transaction à telepaiement@ */
233 $mymail = new HermesMailer();
234 $mymail->setFrom("webmaster@polytechnique.org");
235 $mymail->addTo("telepaiement@staff.polytechnique.org");
236 $mymail->setSubject($conf_title);
237 $msg = "utilisateur : $prenom $nom ($uid)\n".
238 "mail : $forlife@polytechnique.org\n\n".
239 "paiement : $conf_title ($conf_mail)\n".
240 "reference : $champ200\n".
241 "montant : $montant\n\n".
242 "dump de REQUEST:\n".
243 var_export($_REQUEST,true);
244 $mymail->setTxtBody($msg);
245 $mymail->send();
246 exit;
247 }
248
249 function handler_paypal_return(&$page, $uid = null)
250 {
251 if (!empty($GLOBALS['IS_XNET_SITE'])) {
252 new_group_open_page('payment/retour_paypal.tpl');
253 } else {
254 $page->changeTpl('payment/retour_paypal.tpl');
255 }
256 require_once 'diogenes/diogenes.hermes.inc.php';
257
258 /* reference banque (numero de transaction) */
259 $no_transaction = clean_request('tx');
260 /* token a renvoyer pour avoir plus d'information */
261 $clef = clean_request('sig');
262 /* code retour */
263 $status = clean_request('st');
264 /* raison */
265 $reason = ($status == 'Pending')?clean_request('pending_reason'):clean_request('reason_code');
266 /* reference complete de la commande */
267 $fullref = clean_request('cm');
268 /* montant de la transaction */
269 $montant_nb = clean_request('amt');
270 /* devise */
271 $montant_dev = clean_request('cc');
272 $montant = "$montant_nb $montant_dev";
273
274 /* on extrait le code de retour */
275 if ($status != "Completed") {
276 if ($status)
277 paypal_erreur("erreur lors du paiement : $status - $reason");
278 else
279 paypal_erreur("Paiement annulé", false);
280 }
281
282 /* on extrait les informations sur l'utilisateur */
283 $res = XDB::query("
284 SELECT a.prenom,a.nom,a.promo,l.alias,FIND_IN_SET(a.flags,'femme')
285 FROM auth_user_md5 AS a
286 INNER JOIN aliases AS l ON (a.user_id=l.id AND type!='homonyme')
287 WHERE a.user_id={?}", $uid);
288 if (!list($prenom,$nom,$promo,$forlife,$femme) = $res->fetchOneRow()) {
289 paypal_erreur("uid invalide");
290 }
291
292 /* on extrait la reference de la commande */
293 if (!ereg('-xorg-([0-9]+)$',$fullref,$matches)) {
294 paypal_erreur("référence de commande invalide");
295 }
296
297 $ref = $matches[1];
298 $res = XDB::query("SELECT mail,text,confirmation
299 FROM paiement.paiements
300 WHERE id={?}", $ref);
301 if (!list($conf_mail,$conf_title,$conf_text) = $res->fetchOneRow()) {
302 paypal_erreur("référence de commande inconnue");
303 }
304
305 /* on fait l'insertion en base de donnees */
306 XDB::execute("INSERT INTO paiement.transactions (id,uid,ref,fullref,montant,cle,comment)
307 VALUES ({?},{?},{?},{?},{?},{?},{?})",
308 $no_transaction, $uid, $ref, $fullref, $montant, $clef, Env::v('comment'));
309
310 /* on genere le mail de confirmation */
311 $conf_text = str_replace("<prenom>",$prenom,$conf_text);
312 $conf_text = str_replace("<nom>",$nom,$conf_text);
313 $conf_text = str_replace("<promo>",$promo,$conf_text);
314 $conf_text = str_replace("<montant>",$montant,$conf_text);
315 $conf_text = str_replace("<salutation>",$femme ? "Chère" : "Cher",$conf_text);
316 $conf_text = str_replace("<cher>",$femme ? "Chère" : "Cher",$conf_text);
317
318 $mymail = new HermesMailer();
319 $mymail->setFrom($conf_mail);
320 $mymail->addTo("\"$prenom $nom\" <$forlife@polytechnique.org>");
321 $mymail->addCc($conf_mail);
322 $mymail->setSubject($conf_title);
323 $mymail->setTxtBody($conf_text);
324 $mymail->send();
325
326 /* on envoie les details de la transaction à telepaiement@ */
327 $mymail = new HermesMailer();
328 $mymail->setFrom("webmaster@polytechnique.org");
329 $mymail->addTo("telepaiement@polytechnique.org");
330 $mymail->setSubject($conf_title);
331 $msg = "utilisateur : $prenom $nom ($uid)\n".
332 "mail : $forlife@polytechnique.org\n\n".
333 "paiement : $conf_title ($conf_mail)\n".
334 "reference : $no_transaction\n".
335 "montant : $montant\n\n".
336 "dump de REQUEST:\n".
337 var_export($_REQUEST,true);
338 $mymail->setTxtBody($msg);
339 $mymail->send();
340
341 $page->assign('texte', $conf_text);
342 $page->assign('erreur', $erreur);
343 }
344
345 function handler_xnet_payment(&$page, $pid = null)
346 {
347 global $globals;
348
349 if (!is_null($pid)) {
350 return $this->handler_payment($page, $pid);
351 }
352 new_group_page('payment/xnet.tpl');
353
354 $res = XDB::query(
355 "SELECT id, text, url
356 FROM {$globals->money->mpay_tprefix}paiements
357 WHERE asso_id = {?} AND NOT FIND_IN_SET(flags, 'old')
358 ORDER BY id DESC", $globals->asso('id'));
359 $tit = $res->fetchAllAssoc();
360 $page->assign('titres', $tit);
361
362 $order = Env::v('order', 'timestamp');
363 $orders = array('timestamp', 'nom', 'promo', 'montant');
364 if (!in_array($order, $orders)) {
365 $order = 'timestamp';
366 }
367 $inv_order = Env::v('order_inv', 0);
368 $page->assign('order', $order);
369 $page->assign('order_inv', !$inv_order);
370
371 if ($order == 'timestamp') {
372 $inv_order = !$inv_order;
373 }
374
375 if ($inv_order) {
376 $inv_order = ' DESC';
377 } else {
378 $inv_order = '';
379 }
380 if ($order == 'montant') {
381 $order = 'LENGTH(montant) '.$inv_order.', montant';
382 }
383
384 $orderby = 'ORDER BY '.$order.$inv_order;
385 if ($order != 'nom') {
386 $orderby .= ', nom'; $inv_order = '';
387 }
388 $orderby .= ', prenom'.$inv_order;
389 if ($order != 'timestamp') {
390 $orderby .= ', timestamp DESC';
391 }
392
393 $trans = array();
394 $event = array();
395 foreach($tit as $foo) {
396 $pid = $foo['id'];
397 if (may_update()) {
398 $res = XDB::query("SELECT IF(u.nom_usage<>'', u.nom_usage, u.nom) AS nom,
399 u.prenom, u.promo, a.alias, timestamp AS `date`, montant
400 FROM {$globals->money->mpay_tprefix}transactions AS t
401 INNER JOIN auth_user_md5 AS u ON ( t.uid = u.user_id )
402 INNER JOIN aliases AS a ON ( t.uid = a.id AND a.type='a_vie' )
403 WHERE ref = {?} ".$orderby, $pid);
404 $trans[$pid] = $res->fetchAllAssoc();
405 $sum = 0;
406 foreach ($trans[$pid] as $i => $t) {
407 $sum += strtr(substr($t['montant'], 0, strpos($t['montant'], 'EUR')), ',', '.');
408 $trans[$pid][$i]['montant'] = str_replace('EUR', '¤', $t['montant']);
409 }
410 $trans[$pid][] = array('nom' => 'somme totale',
411 'montant' => strtr($sum, '.', ',').' ¤');
412 }
413 $res = XDB::iterRow("SELECT e.eid, e.short_name, e.intitule, ep.nb, ei.montant, ep.paid
414 FROM groupex.evenements AS e
415 LEFT JOIN groupex.evenements_participants AS ep ON (ep.eid = e.eid AND uid = {?})
416 INNER JOIN groupex.evenements_items AS ei ON (ep.eid = ei.eid AND ep.item_id = ei.item_id)
417 WHERE e.paiement_id = {?}",
418 S::v('uid'), $pid);
419 $event[$pid] = array();
420 $event[$pid]['paid'] = 0;
421 if ($res->total()) {
422 $event[$pid]['topay'] = 0;
423 while(list($eid, $shortname, $title, $nb, $montant, $paid) = $res->next()) {
424 $event[$pid]['topay'] += ($nb * $montant);
425 $event[$pid]['eid'] = $eid;
426 $event[$pid]['shortname'] = $shortname;
427 $event[$pid]['title'] = $title;
428 $event[$pid]['ins'] = !is_null($nb);
429 $event[$pid]['paid'] = $paid;
430 }
431 }
432 $res = XDB::query("SELECT montant
433 FROM {$globals->money->mpay_tprefix}transactions AS t
434 WHERE ref = {?} AND uid = {?}", $pid, S::v('uid'));
435 $montants = $res->fetchColumn();
436
437 foreach ($montants as $m) {
438 $p = strtr(substr($m, 0, strpos($m, 'EUR')), ',', '.');
439 $event[$pid]['paid'] += trim($p);
440 }
441 }
442 $page->assign('trans', $trans);
443 $page->assign('event', $event);
444 }
445
446 function handler_admin(&$page, $action = 'list', $id = null) {
447 $page->assign('xorg_title','Polytechnique.org - Administration - Paiements');
448 $page->assign('title', 'Gestion des télépaiements');
449 $table_editor = new PLTableEditor('admin/payments','paiement.paiements','id');
450 $table_editor->add_join_table('paiement.transactions','ref',true);
451 $table_editor->add_sort_field('flags');
452 $table_editor->add_sort_field('id', true, true);
453 $table_editor->on_delete("UPDATE paiement.paiements SET flags = 'old' WHERE id = {?}", "Le paiement a été archivé");
454 $table_editor->describe('text','intitulé',true);
455 $table_editor->describe('url','site web',false);
456 $table_editor->describe('montant_def','montant par défaut',false);
457 $table_editor->describe('montant_min','montant minimum',false);
458 $table_editor->describe('montant_max','montant maximum',false);
459 $table_editor->describe('mail','email contact',true);
460 $table_editor->describe('confirmation','message confirmation',false);
461 $table_editor->apply($page, $action, $id);
462 }
463 }
464
465 ?>