dolibarr  17.0.4
paymentok.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (C) 2001-2002 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3  * Copyright (C) 2006-2013 Laurent Destailleur <eldy@users.sourceforge.net>
4  * Copyright (C) 2012 Regis Houssin <regis.houssin@inodbox.com>
5  * Copyright (C) 2021 WaĆ«l Almoman <info@almoman.com>
6  * Copyright (C) 2021 Maxime Demarest <maxime@indelog.fr>
7  * Copyright (C) 2021 Dorian Vabre <dorian.vabre@gmail.com>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 3 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program. If not, see <https://www.gnu.org/licenses/>.
21  */
22 
32 if (!defined('NOLOGIN')) {
33  define("NOLOGIN", 1); // This means this output page does not require to be logged.
34 }
35 if (!defined('NOCSRFCHECK')) {
36  define("NOCSRFCHECK", 1); // We accept to go on this page from external web site.
37 }
38 if (!defined('NOIPCHECK')) {
39  define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip
40 }
41 if (!defined('NOBROWSERNOTIF')) {
42  define('NOBROWSERNOTIF', '1');
43 }
44 
45 // For MultiCompany module.
46 // Do not use GETPOST here, function is not defined and define must be done before including main.inc.php
47 // TODO This should be useless. Because entity must be retrieve from object ref and not from url.
48 $entity = (!empty($_GET['e']) ? (int) $_GET['e'] : (!empty($_POST['e']) ? (int) $_POST['e'] : 1));
49 if (is_numeric($entity)) {
50  define("DOLENTITY", $entity);
51 }
52 
53 // Load Dolibarr environment
54 require '../../main.inc.php';
55 require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
56 require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
57 require_once DOL_DOCUMENT_ROOT.'/eventorganization/class/conferenceorboothattendee.class.php';
58 require_once DOL_DOCUMENT_ROOT.'/eventorganization/class/conferenceorbooth.class.php';
59 
60 if (isModEnabled('paypal')) {
61  require_once DOL_DOCUMENT_ROOT.'/paypal/lib/paypal.lib.php';
62  require_once DOL_DOCUMENT_ROOT.'/paypal/lib/paypalfunctions.lib.php';
63 }
64 
65 $langs->loadLangs(array("main", "other", "dict", "bills", "companies", "paybox", "paypal"));
66 
67 // Clean parameters
68 if (isModEnabled('paypal')) {
69  $PAYPAL_API_USER = "";
70  if (!empty($conf->global->PAYPAL_API_USER)) {
71  $PAYPAL_API_USER = $conf->global->PAYPAL_API_USER;
72  }
73  $PAYPAL_API_PASSWORD = "";
74  if (!empty($conf->global->PAYPAL_API_PASSWORD)) {
75  $PAYPAL_API_PASSWORD = $conf->global->PAYPAL_API_PASSWORD;
76  }
77  $PAYPAL_API_SIGNATURE = "";
78  if (!empty($conf->global->PAYPAL_API_SIGNATURE)) {
79  $PAYPAL_API_SIGNATURE = $conf->global->PAYPAL_API_SIGNATURE;
80  }
81  $PAYPAL_API_SANDBOX = "";
82  if (!empty($conf->global->PAYPAL_API_SANDBOX)) {
83  $PAYPAL_API_SANDBOX = $conf->global->PAYPAL_API_SANDBOX;
84  }
85  $PAYPAL_API_OK = "";
86  if ($urlok) {
87  $PAYPAL_API_OK = $urlok;
88  }
89  $PAYPAL_API_KO = "";
90  if ($urlko) {
91  $PAYPAL_API_KO = $urlko;
92  }
93 
94  $PAYPALTOKEN = GETPOST('TOKEN');
95  if (empty($PAYPALTOKEN)) {
96  $PAYPALTOKEN = GETPOST('token');
97  }
98  $PAYPALPAYERID = GETPOST('PAYERID');
99  if (empty($PAYPALPAYERID)) {
100  $PAYPALPAYERID = GETPOST('PayerID');
101  }
102 }
103 
104 $FULLTAG = GETPOST('FULLTAG');
105 if (empty($FULLTAG)) {
106  $FULLTAG = GETPOST('fulltag');
107 }
108 $source = GETPOST('s', 'alpha') ? GETPOST('s', 'alpha') : GETPOST('source', 'alpha');
109 $ref = GETPOST('ref');
110 
111 $suffix = GETPOST("suffix", 'aZ09');
112 $membertypeid = GETPOST("membertypeid", 'int');
113 
114 
115 // Detect $paymentmethod
116 $paymentmethod = '';
117 $reg = array();
118 if (preg_match('/PM=([^\.]+)/', $FULLTAG, $reg)) {
119  $paymentmethod = $reg[1];
120 }
121 if (empty($paymentmethod)) {
122  dol_print_error(null, 'The back url does not contains a parameter fulltag that should help us to find the payment method used');
123  exit;
124 }
125 
126 dol_syslog("***** paymentok.php is called paymentmethod=".$paymentmethod." FULLTAG=".$FULLTAG." REQUEST_URI=".$_SERVER["REQUEST_URI"], LOG_DEBUG, 0, '_payment');
127 
128 
129 $validpaymentmethod = array();
130 if (isModEnabled('paypal')) {
131  $validpaymentmethod['paypal'] = 'paypal';
132 }
133 if (isModEnabled('paybox')) {
134  $validpaymentmethod['paybox'] = 'paybox';
135 }
136 if (isModEnabled('stripe')) {
137  $validpaymentmethod['stripe'] = 'stripe';
138 }
139 
140 // Security check
141 if (empty($validpaymentmethod)) {
142  httponly_accessforbidden('No valid payment mode');
143 }
144 
145 
146 $ispaymentok = false;
147 // If payment is ok
148 $PAYMENTSTATUS = $TRANSACTIONID = $TAXAMT = $NOTE = '';
149 // If payment is ko
150 $ErrorCode = $ErrorShortMsg = $ErrorLongMsg = $ErrorSeverityCode = '';
151 
152 
153 $object = new stdClass(); // For triggers
154 
155 $error = 0;
156 
157 
158 /*
159  * Actions
160  */
161 
162 
163 
164 /*
165  * View
166  */
167 
168 $now = dol_now();
169 
170 dol_syslog("Callback url when a payment was done. query_string=".(empty($_SERVER["QUERY_STRING"]) ? '' : dol_escape_htmltag($_SERVER["QUERY_STRING"]))." script_uri=".(empty($_SERVER["SCRIPT_URI"]) ? '' : dol_escape_htmltag($_SERVER["SCRIPT_URI"])), LOG_DEBUG, 0, '_payment');
171 dol_syslog("_SERVER[SERVER_NAME] = ".(empty($_SERVER["SERVER_NAME"]) ? '' : dol_escape_htmltag($_SERVER["SERVER_NAME"])), LOG_DEBUG, 0, '_payment');
172 dol_syslog("_SERVER[SERVER_ADDR] = ".(empty($_SERVER["SERVER_ADDR"]) ? '' : dol_escape_htmltag($_SERVER["SERVER_ADDR"])), LOG_DEBUG, 0, '_payment');
173 
174 $tracepost = "";
175 foreach ($_POST as $k => $v) {
176  if (is_scalar($k) && is_scalar($v)) {
177  $tracepost .= "{$k} - {$v}\n";
178  }
179 }
180 dol_syslog("POST=".$tracepost, LOG_DEBUG, 0, '_payment');
181 $tracesession = "";
182 foreach ($_SESSION as $k => $v) {
183  if (is_scalar($k) && is_scalar($v)) {
184  $tracesession .= "{$k} - {$v}\n";
185  }
186 }
187 dol_syslog("SESSION=".$tracesession, LOG_DEBUG, 0, '_payment');
188 
189 $head = '';
190 if (!empty($conf->global->ONLINE_PAYMENT_CSS_URL)) {
191  $head = '<link rel="stylesheet" type="text/css" href="'.$conf->global->ONLINE_PAYMENT_CSS_URL.'?lang='.$langs->defaultlang.'">'."\n";
192 }
193 
194 $conf->dol_hide_topmenu = 1;
195 $conf->dol_hide_leftmenu = 1;
196 
197 $replacemainarea = (empty($conf->dol_hide_leftmenu) ? '<div>' : '').'<div>';
198 llxHeader($head, $langs->trans("PaymentForm"), '', '', 0, 0, '', '', '', 'onlinepaymentbody', $replacemainarea);
199 
200 
201 // Show message
202 print '<span id="dolpaymentspan"></span>'."\n";
203 print '<div id="dolpaymentdiv" class="center">'."\n";
204 
205 
206 // Show logo (search order: logo defined by PAYMENT_LOGO_suffix, then PAYMENT_LOGO, then small company logo, large company logo, theme logo, common logo)
207 // Define logo and logosmall
208 $logosmall = $mysoc->logo_small;
209 $logo = $mysoc->logo;
210 $paramlogo = 'ONLINE_PAYMENT_LOGO_'.$suffix;
211 if (!empty($conf->global->$paramlogo)) {
212  $logosmall = $conf->global->$paramlogo;
213 } elseif (!empty($conf->global->ONLINE_PAYMENT_LOGO)) {
214  $logosmall = $conf->global->ONLINE_PAYMENT_LOGO;
215 }
216 //print '<!-- Show logo (logosmall='.$logosmall.' logo='.$logo.') -->'."\n";
217 // Define urllogo
218 $urllogo = '';
219 $urllogofull = '';
220 if (!empty($logosmall) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$logosmall)) {
221  $urllogo = DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&amp;entity='.$conf->entity.'&amp;file='.urlencode('logos/thumbs/'.$logosmall);
222  $urllogofull = $dolibarr_main_url_root.'/viewimage.php?modulepart=mycompany&entity='.$conf->entity.'&file='.urlencode('logos/thumbs/'.$logosmall);
223 } elseif (!empty($logo) && is_readable($conf->mycompany->dir_output.'/logos/'.$logo)) {
224  $urllogo = DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&amp;entity='.$conf->entity.'&amp;file='.urlencode('logos/'.$logo);
225  $urllogofull = $dolibarr_main_url_root.'/viewimage.php?modulepart=mycompany&entity='.$conf->entity.'&file='.urlencode('logos/'.$logo);
226 }
227 
228 // Output html code for logo
229 if ($urllogo) {
230  print '<div class="backgreypublicpayment">';
231  print '<div class="logopublicpayment">';
232  print '<img id="dolpaymentlogo" src="'.$urllogo.'"';
233  print '>';
234  print '</div>';
235  if (empty($conf->global->MAIN_HIDE_POWERED_BY)) {
236  print '<div class="poweredbypublicpayment opacitymedium right"><a class="poweredbyhref" href="https://www.dolibarr.org?utm_medium=website&utm_source=poweredby" target="dolibarr" rel="noopener">'.$langs->trans("PoweredBy").'<br><img class="poweredbyimg" src="'.DOL_URL_ROOT.'/theme/dolibarr_logo.svg" width="80px"></a></div>';
237  }
238  print '</div>';
239 }
240 if (!empty($conf->global->MAIN_IMAGE_PUBLIC_PAYMENT)) {
241  print '<div class="backimagepublicpayment">';
242  print '<img id="idMAIN_IMAGE_PUBLIC_PAYMENT" src="'.$conf->global->MAIN_IMAGE_PUBLIC_PAYMENT.'">';
243  print '</div>';
244 }
245 
246 
247 print '<br><br><br>';
248 
249 
250 if (isModEnabled('paypal')) {
251  if ($paymentmethod == 'paypal') { // We call this page only if payment is ok on payment system
252  if ($PAYPALTOKEN) {
253  // Get on url call
254  $onlinetoken = $PAYPALTOKEN;
255  $fulltag = $FULLTAG;
256  $payerID = $PAYPALPAYERID;
257  // Set by newpayment.php
258  $currencyCodeType = $_SESSION['currencyCodeType'];
259  $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"];
260  $paymentType = $_SESSION['PaymentType']; // Value can be 'Mark', 'Sole', 'Sale' for example
261  // From env
262  $ipaddress = $_SESSION['ipaddress'];
263 
264  dol_syslog("Call paymentok with token=".$onlinetoken." paymentType=".$paymentType." currencyCodeType=".$currencyCodeType." payerID=".$payerID." ipaddress=".$ipaddress." FinalPaymentAmt=".$FinalPaymentAmt." fulltag=".$fulltag, LOG_DEBUG, 0, '_payment');
265 
266  // Validate record
267  if (!empty($paymentType)) {
268  dol_syslog("We call GetExpressCheckoutDetails", LOG_DEBUG, 0, '_payment');
269  $resArray = getDetails($onlinetoken);
270  //var_dump($resarray);
271 
272  $ack = strtoupper($resArray["ACK"]);
273  if ($ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING") {
274  // Nothing to do
275  dol_syslog("Call to GetExpressCheckoutDetails return ".$ack, LOG_DEBUG, 0, '_payment');
276  } else {
277  dol_syslog("Call to GetExpressCheckoutDetails return error: ".json_encode($resArray), LOG_WARNING, '_payment');
278  }
279 
280  dol_syslog("We call DoExpressCheckoutPayment token=".$onlinetoken." paymentType=".$paymentType." currencyCodeType=".$currencyCodeType." payerID=".$payerID." ipaddress=".$ipaddress." FinalPaymentAmt=".$FinalPaymentAmt." fulltag=".$fulltag, LOG_DEBUG, 0, '_payment');
281  $resArray2 = confirmPayment($onlinetoken, $paymentType, $currencyCodeType, $payerID, $ipaddress, $FinalPaymentAmt, $fulltag);
282  //var_dump($resarray);
283 
284  $ack = strtoupper($resArray2["ACK"]);
285  if ($ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING") {
286  dol_syslog("Call to GetExpressCheckoutDetails return ".$ack, LOG_DEBUG, 0, '_payment');
287 
288  $object->source = $source;
289  $object->ref = $ref;
290  $object->payerID = $payerID;
291  $object->fulltag = $fulltag;
292  $object->resArray = $resArray2;
293 
294  // resArray was built from a string like that
295  // TOKEN=EC%2d1NJ057703V9359028&TIMESTAMP=2010%2d11%2d01T11%3a40%3a13Z&CORRELATIONID=1efa8c6a36bd8&ACK=Success&VERSION=56&BUILD=1553277&TRANSACTIONID=9B994597K9921420R&TRANSACTIONTYPE=expresscheckout&PAYMENTTYPE=instant&ORDERTIME=2010%2d11%2d01T11%3a40%3a12Z&AMT=155%2e57&FEEAMT=5%2e54&TAXAMT=0%2e00&CURRENCYCODE=EUR&PAYMENTSTATUS=Completed&PENDINGREASON=None&REASONCODE=None
296  $PAYMENTSTATUS = urldecode($resArray2["PAYMENTSTATUS"]); // Should contains 'Completed'
297  $TRANSACTIONID = urldecode($resArray2["TRANSACTIONID"]);
298  $TAXAMT = urldecode($resArray2["TAXAMT"]);
299  $NOTE = urldecode($resArray2["NOTE"]);
300 
301  $ispaymentok = true;
302  } else {
303  dol_syslog("Call to DoExpressCheckoutPayment return error: ".json_encode($resArray2), LOG_WARNING, 0, '_payment');
304 
305  //Display a user friendly Error on the page using any of the following error information returned by PayPal
306  $ErrorCode = urldecode($resArray2["L_ERRORCODE0"]);
307  $ErrorShortMsg = urldecode($resArray2["L_SHORTMESSAGE0"]);
308  $ErrorLongMsg = urldecode($resArray2["L_LONGMESSAGE0"]);
309  $ErrorSeverityCode = urldecode($resArray2["L_SEVERITYCODE0"]);
310  }
311  } else {
312  $ErrorCode = "SESSIONEXPIRED";
313  $ErrorLongMsg = "Session expired. Can't retreive PaymentType. Payment has not been validated.";
314  $ErrorShortMsg = "Session expired";
315 
316  dol_syslog($ErrorLongMsg, LOG_WARNING, 0, '_payment');
317  dol_print_error('', 'Session expired');
318  }
319  } else {
320  $ErrorCode = "PAYPALTOKENNOTDEFINED";
321  $ErrorLongMsg = "The parameter PAYPALTOKEN was not defined. Payment has not been validated.";
322  $ErrorShortMsg = "Parameter PAYPALTOKEN not defined";
323 
324  dol_syslog($ErrorLongMsg, LOG_WARNING, 0, '_payment');
325  dol_print_error('', 'PAYPALTOKEN not defined');
326  }
327  }
328 }
329 
330 if (isModEnabled('paybox')) {
331  if ($paymentmethod == 'paybox') {
332  // TODO Add a check to validate that payment is ok.
333  $ispaymentok = true; // We call this page only if payment is ok on payment system
334  }
335 }
336 
337 if (isModEnabled('stripe')) {
338  if ($paymentmethod == 'stripe') {
339  // TODO Add a check to validate that payment is ok. We can request Stripe with payment_intent and payment_intent_client_secret
340  $ispaymentok = true; // We call this page only if payment is ok on payment system
341  }
342 }
343 
344 
345 // If data not provided from back url, search them into the session env
346 if (empty($ipaddress)) {
347  $ipaddress = $_SESSION['ipaddress'];
348 }
349 if (empty($TRANSACTIONID)) {
350  $TRANSACTIONID = $_SESSION['TRANSACTIONID'];
351  if (empty($TRANSACTIONID) && GETPOST('payment_intent', 'alphanohtml')) {
352  // For the case we use STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION = 2
353  $TRANSACTIONID = GETPOST('payment_intent', 'alphanohtml');
354  }
355 }
356 if (empty($FinalPaymentAmt)) {
357  $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"];
358 }
359 if (empty($currencyCodeType)) {
360  $currencyCodeType = $_SESSION['currencyCodeType'];
361 }
362 // Seems used onyl by Paypal
363 if (empty($paymentType)) {
364  $paymentType = $_SESSION["paymentType"];
365 }
366 
367 $fulltag = $FULLTAG;
368 $tmptag = dolExplodeIntoArray($fulltag, '.', '=');
369 
370 
371 dol_syslog("ispaymentok=".$ispaymentok." tmptag=".var_export($tmptag, true), LOG_DEBUG, 0, '_payment');
372 
373 
374 // Make complementary actions
375 $ispostactionok = 0;
376 $postactionmessages = array();
377 if ($ispaymentok) {
378  // Set permission for the anonymous user
379  if (empty($user->rights->societe)) {
380  $user->rights->societe = new stdClass();
381  }
382  if (empty($user->rights->facture)) {
383  $user->rights->facture = new stdClass();
384  $user->rights->facture->invoice_advance = new stdClass();
385  }
386  if (empty($user->rights->adherent)) {
387  $user->rights->adherent = new stdClass();
388  $user->rights->adherent->cotisation = new stdClass();
389  }
390  $user->rights->societe->creer = 1;
391  $user->rights->facture->creer = 1;
392  $user->rights->facture->invoice_advance->validate = 1;
393  $user->rights->adherent->cotisation->creer = 1;
394 
395  if (array_key_exists('MEM', $tmptag) && $tmptag['MEM'] > 0) {
396  // Validate member
397  // Create subscription
398  // Create complementary actions (this include creation of thirdparty)
399  // Send confirmation email
400 
401  // Record subscription
402  include_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
403  include_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent_type.class.php';
404  include_once DOL_DOCUMENT_ROOT.'/adherents/class/subscription.class.php';
405  $adht = new AdherentType($db);
406  $object = new Adherent($db);
407 
408  $result1 = $object->fetch((int) $tmptag['MEM']);
409  $result2 = $adht->fetch($object->typeid);
410 
411  $defaultdelay = !empty($adht->duration_value) ? $adht->duration_value : 1;
412  $defaultdelayunit = !empty($adht->duration_unit) ? $adht->duration_unit : 'y';
413 
414  dol_syslog("We have to process member with id=".$tmptag['MEM']." result1=".$result1." result2=".$result2, LOG_DEBUG, 0, '_payment');
415 
416  if ($result1 > 0 && $result2 > 0) {
417  $paymentTypeId = 0;
418  if ($paymentmethod == 'paybox') {
419  $paymentTypeId = $conf->global->PAYBOX_PAYMENT_MODE_FOR_PAYMENTS;
420  }
421  if ($paymentmethod == 'paypal') {
422  $paymentTypeId = $conf->global->PAYPAL_PAYMENT_MODE_FOR_PAYMENTS;
423  }
424  if ($paymentmethod == 'stripe') {
425  $paymentTypeId = $conf->global->STRIPE_PAYMENT_MODE_FOR_PAYMENTS;
426  }
427  if (empty($paymentTypeId)) {
428  dol_syslog("paymentType = ".$paymentType, LOG_DEBUG, 0, '_payment');
429 
430  if (empty($paymentType)) {
431  $paymentType = 'CB';
432  }
433  // May return nothing when paymentType means nothing
434  // (for example when paymentType is 'Mark', 'Sole', 'Sale', for paypal)
435  $paymentTypeId = dol_getIdFromCode($db, $paymentType, 'c_paiement', 'code', 'id', 1);
436 
437  // If previous line has returned nothing, we force to get the ID of payment of Credit Card (hard coded code 'CB').
438  if (empty($paymentTypeId) || $paymentTypeId < 0) {
439  $paymentTypeId = dol_getIdFromCode($db, 'CB', 'c_paiement', 'code', 'id', 1);
440  }
441  }
442 
443  dol_syslog("FinalPaymentAmt=".$FinalPaymentAmt." paymentTypeId=".$paymentTypeId." currencyCodeType=".$currencyCodeType, LOG_DEBUG, 0, '_payment');
444 
445  // Do action only if $FinalPaymentAmt is set (session variable is cleaned after this page to avoid duplicate actions when page is POST a second time)
446  if (!empty($FinalPaymentAmt) && $paymentTypeId > 0) {
447  // Security protection:
448  if (empty($adht->caneditamount)) { // If we didn't allow members to choose their membership amount (if the amount is allowed in edit mode, no need to check)
449  if ($object->status == $object::STATUS_DRAFT) { // If the member is not yet validated, we check that the amount is the same as expected.
450  $typeid = $object->typeid;
451 
452  // Set amount for the subscription:
453  // - First check the amount of the member type.
454  $amountbytype = $adht->amountByType(1); // Load the array of amount per type
455  $amountexpected = empty($amountbytype[$typeid]) ? 0 : $amountbytype[$typeid];
456  // - If not found, take the default amount
457  if (empty($amountexpected) && !empty($conf->global->MEMBER_NEWFORM_AMOUNT)) {
458  $amountexpected = $conf->global->MEMBER_NEWFORM_AMOUNT;
459  }
460 
461  if ($amountexpected && $amountexpected != $FinalPaymentAmt) {
462  $error++;
463  $errmsg = 'Value of FinalPayment ('.$FinalPaymentAmt.') differs from value expected for membership ('.$amountexpected.'). May be a hack to try to pay a different amount ?';
464  $postactionmessages[] = $errmsg;
465  $ispostactionok = -1;
466  dol_syslog("Failed to validate member (bad amount check): ".$errmsg, LOG_ERR, 0, '_payment');
467  }
468  }
469  }
470 
471  // Security protection:
472  if (!empty($conf->global->MEMBER_MIN_AMOUNT)) {
473  if ($FinalPaymentAmt < $conf->global->MEMBER_MIN_AMOUNT) {
474  $error++;
475  $errmsg = 'Value of FinalPayment ('.$FinalPaymentAmt.') is lower than the minimum allowed ('.$conf->global->MEMBER_MIN_AMOUNT.'). May be a hack to try to pay a different amount ?';
476  $postactionmessages[] = $errmsg;
477  $ispostactionok = -1;
478  dol_syslog("Failed to validate member (amount lower than minimum): ".$errmsg, LOG_ERR, 0, '_payment');
479  }
480  }
481 
482  // Security protection:
483  if ($currencyCodeType && $currencyCodeType != $conf->currency) { // Check that currency is the good one
484  $error++;
485  $errmsg = 'Value of currencyCodeType ('.$currencyCodeType.') differs from value expected for membership ('.$conf->currency.'). May be a hack to try to pay a different amount ?';
486  $postactionmessages[] = $errmsg;
487  $ispostactionok = -1;
488  dol_syslog("Failed to validate member (bad currency check): ".$errmsg, LOG_ERR, 0, '_payment');
489  }
490 
491  if (! $error) {
492  // We validate the member (no effect if it is already validated)
493  $result = ($object->status == $object::STATUS_EXCLUDED) ? -1 : $object->validate($user); // if membre is excluded (status == -2) the new validation is not possible
494  if ($result < 0 || empty($object->datevalid)) {
495  $error++;
496  $errmsg = $object->error;
497  $postactionmessages[] = $errmsg;
498  $postactionmessages = array_merge($postactionmessages, $object->errors);
499  $ispostactionok = -1;
500  dol_syslog("Failed to validate member: ".$errmsg, LOG_ERR, 0, '_payment');
501  }
502  }
503 
504  // Subscription informations
505  $datesubscription = $object->datevalid;
506  if ($object->datefin > 0) {
507  $datesubscription = dol_time_plus_duree($object->datefin, 1, 'd');
508  }
509 
510  $datesubend = null;
511  if ($datesubscription && $defaultdelay && $defaultdelayunit) {
512  $datesubend = dol_time_plus_duree($datesubscription, $defaultdelay, $defaultdelayunit);
513  // the new end date of subscription must be in futur
514  while ($datesubend < $now) {
515  $datesubend = dol_time_plus_duree($datesubend, $defaultdelay, $defaultdelayunit);
516  $datesubscription = dol_time_plus_duree($datesubscription, $defaultdelay, $defaultdelayunit);
517  }
518  $datesubend = dol_time_plus_duree($datesubend, -1, 'd');
519  }
520 
521  // Set output language
522  $outputlangs = new Translate('', $conf);
523  $outputlangs->setDefaultLang(empty($object->thirdparty->default_lang) ? $mysoc->default_lang : $object->thirdparty->default_lang);
524  $paymentdate = $now;
525  $amount = $FinalPaymentAmt;
526  $formatteddate = dol_print_date($paymentdate, 'dayhour', 'auto', $outputlangs);
527  $label = $langs->trans("OnlineSubscriptionPaymentLine", $formatteddate, $paymentmethod, $ipaddress, $TRANSACTIONID);
528 
529  // Payment informations
530  $accountid = 0;
531  if ($paymentmethod == 'paybox') {
532  $accountid = $conf->global->PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS;
533  }
534  if ($paymentmethod == 'paypal') {
535  $accountid = $conf->global->PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS;
536  }
537  if ($paymentmethod == 'stripe') {
538  $accountid = $conf->global->STRIPE_BANK_ACCOUNT_FOR_PAYMENTS;
539  }
540  if ($accountid < 0) {
541  $error++;
542  $errmsg = 'Setup of bank account to use for payment is not correctly done for payment method '.$paymentmethod;
543  $postactionmessages[] = $errmsg;
544  $ispostactionok = -1;
545  dol_syslog("Failed to get the bank account to record payment: ".$errmsg, LOG_ERR, 0, '_payment');
546  }
547 
548  $operation = dol_getIdFromCode($db, $paymentTypeId, 'c_paiement', 'id', 'code', 1); // Payment mode code returned from payment mode id
549  $num_chq = '';
550  $emetteur_nom = '';
551  $emetteur_banque = '';
552  // Define default choice for complementary actions
553  $option = '';
554  if (!empty($conf->global->ADHERENT_BANK_USE) && $conf->global->ADHERENT_BANK_USE == 'bankviainvoice' && isModEnabled("banque") && isModEnabled("societe") && isModEnabled('facture')) {
555  $option = 'bankviainvoice';
556  } elseif (!empty($conf->global->ADHERENT_BANK_USE) && $conf->global->ADHERENT_BANK_USE == 'bankdirect' && isModEnabled("banque")) {
557  $option = 'bankdirect';
558  } elseif (!empty($conf->global->ADHERENT_BANK_USE) && $conf->global->ADHERENT_BANK_USE == 'invoiceonly' && isModEnabled("banque") && isModEnabled("societe") && isModEnabled('facture')) {
559  $option = 'invoiceonly';
560  }
561  if (empty($option)) {
562  $option = 'none';
563  }
564  $sendalsoemail = 1;
565 
566  // Record the subscription then complementary actions
567  $db->begin();
568 
569  // Create subscription
570  if (!$error) {
571  dol_syslog("Call ->subscription to create subscription", LOG_DEBUG, 0, '_payment');
572 
573  $crowid = $object->subscription($datesubscription, $amount, $accountid, $operation, $label, $num_chq, $emetteur_nom, $emetteur_banque, $datesubend, $membertypeid);
574  if ($crowid <= 0) {
575  $error++;
576  $errmsg = $object->error;
577  $postactionmessages[] = $errmsg;
578  $ispostactionok = -1;
579  } else {
580  $postactionmessages[] = 'Subscription created (id='.$crowid.')';
581  $ispostactionok = 1;
582  }
583  }
584 
585  if (!$error) {
586  dol_syslog("Call ->subscriptionComplementaryActions option=".$option, LOG_DEBUG, 0, '_payment');
587 
588  $autocreatethirdparty = 1; // will create thirdparty if member not yet linked to a thirdparty
589 
590  $result = $object->subscriptionComplementaryActions($crowid, $option, $accountid, $datesubscription, $paymentdate, $operation, $label, $amount, $num_chq, $emetteur_nom, $emetteur_banque, $autocreatethirdparty, $TRANSACTIONID, $service);
591  if ($result < 0) {
592  dol_syslog("Error ".$object->error." ".join(',', $object->errors), LOG_DEBUG, 0, '_payment');
593 
594  $error++;
595  $postactionmessages[] = $object->error;
596  $postactionmessages = array_merge($postactionmessages, $object->errors);
597  $ispostactionok = -1;
598  } else {
599  if ($option == 'bankviainvoice') {
600  $postactionmessages[] = 'Invoice, payment and bank record created';
601  dol_syslog("Invoice, payment and bank record created", LOG_DEBUG, 0, '_payment');
602  }
603  if ($option == 'bankdirect') {
604  $postactionmessages[] = 'Bank record created';
605  dol_syslog("Bank record created", LOG_DEBUG, 0, '_payment');
606  }
607  if ($option == 'invoiceonly') {
608  $postactionmessages[] = 'Invoice recorded';
609  dol_syslog("Invoice recorded", LOG_DEBUG, 0, '_payment');
610  }
611  $ispostactionok = 1;
612 
613  // If an invoice was created, it is into $object->invoice
614  }
615  }
616 
617  if (!$error) {
618  if ($paymentmethod == 'stripe' && $autocreatethirdparty && $option == 'bankviainvoice') {
619  $thirdparty_id = $object->fk_soc;
620 
621  dol_syslog("Search existing Stripe customer profile for thirdparty_id=".$thirdparty_id, LOG_DEBUG, 0, '_payment');
622 
623  $service = 'StripeTest';
624  $servicestatus = 0;
625  if (!empty($conf->global->STRIPE_LIVE) && !GETPOST('forcesandbox', 'alpha')) {
626  $service = 'StripeLive';
627  $servicestatus = 1;
628  }
629  $stripeacc = null; // No Oauth/connect use for public pages
630 
631  $thirdparty = new Societe($db);
632  $thirdparty->fetch($thirdparty_id);
633 
634  include_once DOL_DOCUMENT_ROOT.'/stripe/class/stripe.class.php'; // This also set $stripearrayofkeysbyenv
635  $stripe = new Stripe($db);
636  //$stripeacc = $stripe->getStripeAccount($service); Already defined previously
637 
638  $customer = $stripe->customerStripe($thirdparty, $stripeacc, $servicestatus, 0);
639 
640  if (!$customer && $TRANSACTIONID) { // Not linked to a stripe customer, we make the link
641  dol_syslog("No stripe profile found, so we add it for TRANSACTIONID = ".$TRANSACTIONID, LOG_DEBUG, 0, '_payment');
642 
643  try {
644  global $stripearrayofkeysbyenv;
645  \Stripe\Stripe::setApiKey($stripearrayofkeysbyenv[$servicestatus]['secret_key']);
646 
647  if (preg_match('/^pi_/', $TRANSACTIONID)) {
648  // This may throw an error if not found.
649  $chpi = \Stripe\PaymentIntent::retrieve($TRANSACTIONID); // payment_intent (pi_...)
650  } else {
651  // This throw an error if not found
652  $chpi = \Stripe\Charge::retrieve($TRANSACTIONID); // old method, contains the charge id (ch_...)
653  }
654 
655  if ($chpi) {
656  $stripecu = $chpi->customer; // value 'cus_....'. WARNING: This property may be empty if first payment was recorded before the stripe customer was created.
657 
658  if (empty($stripecu)) {
659  // This include the INSERT
660  $customer = $stripe->customerStripe($thirdparty, $stripeacc, $servicestatus, 1);
661 
662  // Link this customer to the payment intent
663  if (preg_match('/^pi_/', $TRANSACTIONID) && $customer) {
664  \Stripe\PaymentIntent::update($chpi->id, array('customer' => $customer->id));
665  }
666  } else {
667  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_account (fk_soc, login, key_account, site, site_account, status, entity, date_creation, fk_user_creat)";
668  $sql .= " VALUES (".((int) $object->fk_soc).", '', '".$db->escape($stripecu)."', 'stripe', '".$db->escape($stripearrayofkeysbyenv[$servicestatus]['publishable_key'])."', ".((int) $servicestatus).", ".((int) $conf->entity).", '".$db->idate(dol_now())."', 0)";
669  $resql = $db->query($sql);
670  if (!$resql) { // should not happen
671  $error++;
672  $errmsg = 'Failed to insert customer stripe id in database : '.$db->lasterror();
673  dol_syslog($errmsg, LOG_ERR, 0, '_payment');
674  $postactionmessages[] = $errmsg;
675  $ispostactionok = -1;
676  }
677  }
678  } else { // should not happen
679  $error++;
680  $errmsg = 'Failed to retreive paymentintent or charge from id';
681  dol_syslog($errmsg, LOG_ERR, 0, '_payment');
682  $postactionmessages[] = $errmsg;
683  $ispostactionok = -1;
684  }
685  } catch (Exception $e) { // should not happen
686  $error++;
687  $errmsg = 'Failed to get or save customer stripe id in database : '.$e->getMessage();
688  dol_syslog($errmsg, LOG_ERR, 0, '_payment');
689  $postactionmessages[] = $errmsg;
690  $ispostactionok = -1;
691  }
692  }
693  }
694  }
695 
696  if (!$error) {
697  $db->commit();
698  } else {
699  $db->rollback();
700  }
701 
702  // Send email to member
703  if (!$error) {
704  dol_syslog("Send email to customer to ".$object->email." if we have to (sendalsoemail = ".$sendalsoemail.")", LOG_DEBUG, 0, '_payment');
705 
706  // Send confirmation Email
707  if ($object->email && $sendalsoemail) {
708  $subject = '';
709  $msg = '';
710 
711  // Send subscription email
712  include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
713  $formmail = new FormMail($db);
714  // Load traductions files required by page
715  $outputlangs->loadLangs(array("main", "members"));
716  // Get email content from template
717  $arraydefaultmessage = null;
718  $labeltouse = $conf->global->ADHERENT_EMAIL_TEMPLATE_SUBSCRIPTION;
719 
720  if (!empty($labeltouse)) {
721  $arraydefaultmessage = $formmail->getEMailTemplate($db, 'member', $user, $outputlangs, 0, 1, $labeltouse);
722  }
723 
724  if (!empty($labeltouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) {
725  $subject = $arraydefaultmessage->topic;
726  $msg = $arraydefaultmessage->content;
727  }
728 
729  $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $object);
730 
731  // Create external user
732  if (!empty($conf->global->ADHERENT_CREATE_EXTERNAL_USER_LOGIN)) {
733  $infouserlogin = '';
734  $nuser = new User($db);
735  $tmpuser = dol_clone($object);
736 
737  $result = $nuser->create_from_member($tmpuser, $object->login);
738  $newpassword = $nuser->setPassword($user, '');
739 
740  if ($result < 0) {
741  $outputlangs->load("errors");
742  $postactionmessages[] = 'Error in create external user : '.$nuser->error;
743  } else {
744  $infouserlogin = $outputlangs->trans("Login").': '.$nuser->login.' '."\n".$outputlangs->trans("Password").': '.$newpassword;
745  $postactionmessages[] = $langs->trans("NewUserCreated", $nuser->login);
746  }
747  $substitutionarray['__MEMBER_USER_LOGIN_INFORMATION__'] = $infouserlogin;
748  }
749 
750  complete_substitutions_array($substitutionarray, $outputlangs, $object);
751  $subjecttosend = make_substitutions($subject, $substitutionarray, $outputlangs);
752  $texttosend = make_substitutions(dol_concatdesc($msg, $adht->getMailOnSubscription()), $substitutionarray, $outputlangs);
753 
754  // Attach a file ?
755  $file = '';
756  $listofpaths = array();
757  $listofnames = array();
758  $listofmimes = array();
759  if (is_object($object->invoice)) {
760  $invoicediroutput = $conf->facture->dir_output;
761  $fileparams = dol_most_recent_file($invoicediroutput.'/'.$object->invoice->ref, preg_quote($object->invoice->ref, '/').'[^\-]+');
762  $file = $fileparams['fullname'];
763 
764  $listofpaths = array($file);
765  $listofnames = array(basename($file));
766  $listofmimes = array(dol_mimetype($file));
767  }
768 
769  $moreinheader = 'X-Dolibarr-Info: send_an_email by public/payment/paymentok.php'."\r\n";
770 
771  $result = $object->send_an_email($texttosend, $subjecttosend, $listofpaths, $listofmimes, $listofnames, "", "", 0, -1, "", $moreinheader);
772 
773  if ($result < 0) {
774  $errmsg = $object->error;
775  $postactionmessages[] = $errmsg;
776  $ispostactionok = -1;
777  } else {
778  if ($file) {
779  $postactionmessages[] = 'Email sent to member (with invoice document attached)';
780  } else {
781  $postactionmessages[] = 'Email sent to member (without any attached document)';
782  }
783 
784  // TODO Add actioncomm event
785  }
786  }
787  }
788  } else {
789  $postactionmessages[] = 'Failed to get a valid value for "amount paid" or "payment type" to record the payment of subscription for member '.$tmptag['MEM'].'. May be payment was already recorded.';
790  $ispostactionok = -1;
791  }
792  } else {
793  $postactionmessages[] = 'Member '.$tmptag['MEM'].' for subscription paid was not found';
794  $ispostactionok = -1;
795  }
796  } elseif (array_key_exists('INV', $tmptag) && $tmptag['INV'] > 0) {
797  // Record payment
798  include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
799  $object = new Facture($db);
800  $result = $object->fetch((int) $tmptag['INV']);
801  if ($result) {
802  $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"];
803 
804  $paymentTypeId = 0;
805  if ($paymentmethod == 'paybox') {
806  $paymentTypeId = $conf->global->PAYBOX_PAYMENT_MODE_FOR_PAYMENTS;
807  }
808  if ($paymentmethod == 'paypal') {
809  $paymentTypeId = $conf->global->PAYPAL_PAYMENT_MODE_FOR_PAYMENTS;
810  }
811  if ($paymentmethod == 'stripe') {
812  $paymentTypeId = $conf->global->STRIPE_PAYMENT_MODE_FOR_PAYMENTS;
813  }
814  if (empty($paymentTypeId)) {
815  dol_syslog("paymentType = ".$paymentType, LOG_DEBUG, 0, '_payment');
816 
817  if (empty($paymentType)) {
818  $paymentType = 'CB';
819  }
820  // May return nothing when paymentType means nothing
821  // (for example when paymentType is 'Mark', 'Sole', 'Sale', for paypal)
822  $paymentTypeId = dol_getIdFromCode($db, $paymentType, 'c_paiement', 'code', 'id', 1);
823 
824  // If previous line has returned nothing, we force to get the ID of payment of Credit Card (hard coded code 'CB').
825  if (empty($paymentTypeId) || $paymentTypeId < 0) {
826  $paymentTypeId = dol_getIdFromCode($db, 'CB', 'c_paiement', 'code', 'id', 1);
827  }
828  }
829 
830  dol_syslog("FinalPaymentAmt = ".$FinalPaymentAmt." paymentTypeId = ".$paymentTypeId, LOG_DEBUG, 0, '_payment');
831 
832  // Do action only if $FinalPaymentAmt is set (session variable is cleaned after this page to avoid duplicate actions when page is POST a second time)
833  if (!empty($FinalPaymentAmt) && $paymentTypeId > 0) {
834  $db->begin();
835 
836  // Creation of payment line
837  include_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
838  $paiement = new Paiement($db);
839  $paiement->datepaye = $now;
840  if ($currencyCodeType == $conf->currency) {
841  $paiement->amounts = array($object->id => $FinalPaymentAmt); // Array with all payments dispatching with invoice id
842  } else {
843  $paiement->multicurrency_amounts = array($object->id => $FinalPaymentAmt); // Array with all payments dispatching
844 
845  $postactionmessages[] = 'Payment was done in a different currency that currency expected of company';
846  $ispostactionok = -1;
847  $error++; // Not yet supported
848  }
849  $paiement->paiementid = $paymentTypeId;
850  $paiement->num_payment = '';
851  $paiement->note_public = 'Online payment '.dol_print_date($now, 'standard').' from '.$ipaddress;
852  $paiement->ext_payment_id = $TRANSACTIONID;
853  $paiement->ext_payment_site = $service;
854 
855  if (!$error) {
856  $paiement_id = $paiement->create($user, 1); // This include closing invoices and regenerating documents
857  if ($paiement_id < 0) {
858  $postactionmessages[] = $paiement->error.' '.join("<br>\n", $paiement->errors);
859  $ispostactionok = -1;
860  $error++;
861  } else {
862  $postactionmessages[] = 'Payment created';
863  $ispostactionok = 1;
864  }
865  }
866 
867  if (!$error && isModEnabled("banque")) {
868  $bankaccountid = 0;
869  if ($paymentmethod == 'paybox') {
870  $bankaccountid = $conf->global->PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS;
871  } elseif ($paymentmethod == 'paypal') {
872  $bankaccountid = $conf->global->PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS;
873  } elseif ($paymentmethod == 'stripe') {
874  $bankaccountid = $conf->global->STRIPE_BANK_ACCOUNT_FOR_PAYMENTS;
875  }
876 
877  if ($bankaccountid > 0) {
878  $label = '(CustomerInvoicePayment)';
879  if ($object->type == Facture::TYPE_CREDIT_NOTE) {
880  $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
881  }
882  $result = $paiement->addPaymentToBank($user, 'payment', $label, $bankaccountid, '', '');
883  if ($result < 0) {
884  $postactionmessages[] = $paiement->error.' '.join("<br>\n", $paiement->errors);
885  $ispostactionok = -1;
886  $error++;
887  } else {
888  $postactionmessages[] = 'Bank transaction of payment created';
889  $ispostactionok = 1;
890  }
891  } else {
892  $postactionmessages[] = 'Setup of bank account to use in module '.$paymentmethod.' was not set. Your payment was really executed but we failed to record it. Please contact us.';
893  $ispostactionok = -1;
894  $error++;
895  }
896  }
897 
898  if (!$error) {
899  $db->commit();
900  } else {
901  $db->rollback();
902  }
903  } else {
904  $postactionmessages[] = 'Failed to get a valid value for "amount paid" ('.$FinalPaymentAmt.') or "payment type id" ('.$paymentTypeId.') to record the payment of invoice '.$tmptag['INV'].'. May be payment was already recorded.';
905  $ispostactionok = -1;
906  }
907  } else {
908  $postactionmessages[] = 'Invoice paid '.$tmptag['INV'].' was not found';
909  $ispostactionok = -1;
910  }
911  } elseif (array_key_exists('ORD', $tmptag) && $tmptag['ORD'] > 0) {
912  include_once DOL_DOCUMENT_ROOT . '/commande/class/commande.class.php';
913  $object = new Commande($db);
914  $result = $object->fetch((int) $tmptag['ORD']);
915  if ($result) {
916  $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"];
917 
918  $paymentTypeId = 0;
919  if ($paymentmethod == 'paybox') {
920  $paymentTypeId = $conf->global->PAYBOX_PAYMENT_MODE_FOR_PAYMENTS;
921  }
922  if ($paymentmethod == 'paypal') {
923  $paymentTypeId = $conf->global->PAYPAL_PAYMENT_MODE_FOR_PAYMENTS;
924  }
925  if ($paymentmethod == 'stripe') {
926  $paymentTypeId = $conf->global->STRIPE_PAYMENT_MODE_FOR_PAYMENTS;
927  }
928  if (empty($paymentTypeId)) {
929  dol_syslog("paymentType = ".$paymentType, LOG_DEBUG, 0, '_payment');
930 
931  if (empty($paymentType)) {
932  $paymentType = 'CB';
933  }
934  // May return nothing when paymentType means nothing
935  // (for example when paymentType is 'Mark', 'Sole', 'Sale', for paypal)
936  $paymentTypeId = dol_getIdFromCode($db, $paymentType, 'c_paiement', 'code', 'id', 1);
937 
938  // If previous line has returned nothing, we force to get the ID of payment of Credit Card (hard coded code 'CB').
939  if (empty($paymentTypeId) || $paymentTypeId < 0) {
940  $paymentTypeId = dol_getIdFromCode($db, 'CB', 'c_paiement', 'code', 'id', 1);
941  }
942  }
943 
944  // Do action only if $FinalPaymentAmt is set (session variable is cleaned after this page to avoid duplicate actions when page is POST a second time)
945  if (isModEnabled('facture')) {
946  if (!empty($FinalPaymentAmt) && $paymentTypeId > 0 ) {
947  include_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
948  $invoice = new Facture($db);
949  $result = $invoice->createFromOrder($object, $user);
950  if ($result > 0) {
951  $object->classifyBilled($user);
952  $invoice->validate($user);
953  // Creation of payment line
954  include_once DOL_DOCUMENT_ROOT . '/compta/paiement/class/paiement.class.php';
955  $paiement = new Paiement($db);
956  $paiement->datepaye = $now;
957  if ($currencyCodeType == $conf->currency) {
958  $paiement->amounts = array($invoice->id => $FinalPaymentAmt); // Array with all payments dispatching with invoice id
959  } else {
960  $paiement->multicurrency_amounts = array($invoice->id => $FinalPaymentAmt); // Array with all payments dispatching
961 
962  $postactionmessages[] = 'Payment was done in a different currency that currency expected of company';
963  $ispostactionok = -1;
964  $error++;
965  }
966  $paiement->paiementid = $paymentTypeId;
967  $paiement->num_payment = '';
968  $paiement->note_public = 'Online payment ' . dol_print_date($now, 'standard') . ' from ' . $ipaddress;
969  $paiement->ext_payment_id = $TRANSACTIONID;
970  $paiement->ext_payment_site = '';
971 
972  if (!$error) {
973  $paiement_id = $paiement->create($user, 1); // This include closing invoices and regenerating documents
974  if ($paiement_id < 0) {
975  $postactionmessages[] = $paiement->error . ' ' . join("<br>\n", $paiement->errors);
976  $ispostactionok = -1;
977  $error++;
978  } else {
979  $postactionmessages[] = 'Payment created';
980  $ispostactionok = 1;
981  }
982  }
983 
984  if (!$error && isModEnabled("banque")) {
985  $bankaccountid = 0;
986  if ($paymentmethod == 'paybox') $bankaccountid = $conf->global->PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS;
987  elseif ($paymentmethod == 'paypal') $bankaccountid = $conf->global->PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS;
988  elseif ($paymentmethod == 'stripe') $bankaccountid = $conf->global->STRIPE_BANK_ACCOUNT_FOR_PAYMENTS;
989 
990  if ($bankaccountid > 0) {
991  $label = '(CustomerInvoicePayment)';
992  if ($object->type == Facture::TYPE_CREDIT_NOTE) $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
993  $result = $paiement->addPaymentToBank($user, 'payment', $label, $bankaccountid, '', '');
994  if ($result < 0) {
995  $postactionmessages[] = $paiement->error . ' ' . join("<br>\n", $paiement->errors);
996  $ispostactionok = -1;
997  $error++;
998  } else {
999  $postactionmessages[] = 'Bank transaction of payment created';
1000  $ispostactionok = 1;
1001  }
1002  } else {
1003  $postactionmessages[] = 'Setup of bank account to use in module ' . $paymentmethod . ' was not set. No way to record the payment.';
1004  $ispostactionok = -1;
1005  $error++;
1006  }
1007  }
1008 
1009  if (!$error) {
1010  $db->commit();
1011  } else {
1012  $db->rollback();
1013  }
1014  } else {
1015  $postactionmessages[] = 'Failed to create invoice form order ' . $tmptag['ORD'] . '.';
1016  $ispostactionok = -1;
1017  }
1018  } else {
1019  $postactionmessages[] = 'Failed to get a valid value for "amount paid" (' . $FinalPaymentAmt . ') or "payment type id" (' . $paymentTypeId . ') to record the payment of order ' . $tmptag['ORD'] . '. May be payment was already recorded.';
1020  $ispostactionok = -1;
1021  }
1022  } else {
1023  $postactionmessages[] = 'Invoice module is not enable';
1024  $ispostactionok = -1;
1025  }
1026  } else {
1027  $postactionmessages[] = 'Order paid ' . $tmptag['ORD'] . ' was not found';
1028  $ispostactionok = -1;
1029  }
1030  } elseif (array_key_exists('DON', $tmptag) && $tmptag['DON'] > 0) {
1031  include_once DOL_DOCUMENT_ROOT.'/don/class/don.class.php';
1032  $don = new Don($db);
1033  $result = $don->fetch((int) $tmptag['DON']);
1034  if ($result) {
1035  $paymentTypeId = 0;
1036  if ($paymentmethod == 'paybox') {
1037  $paymentTypeId = $conf->global->PAYBOX_PAYMENT_MODE_FOR_PAYMENTS;
1038  }
1039  if ($paymentmethod == 'paypal') {
1040  $paymentTypeId = $conf->global->PAYPAL_PAYMENT_MODE_FOR_PAYMENTS;
1041  }
1042  if ($paymentmethod == 'stripe') {
1043  $paymentTypeId = $conf->global->STRIPE_PAYMENT_MODE_FOR_PAYMENTS;
1044  }
1045  if (empty($paymentTypeId)) {
1046  dol_syslog("paymentType = ".$paymentType, LOG_DEBUG, 0, '_payment');
1047 
1048  if (empty($paymentType)) {
1049  $paymentType = 'CB';
1050  }
1051  // May return nothing when paymentType means nothing
1052  // (for example when paymentType is 'Mark', 'Sole', 'Sale', for paypal)
1053  $paymentTypeId = dol_getIdFromCode($db, $paymentType, 'c_paiement', 'code', 'id', 1);
1054 
1055  // If previous line has returned nothing, we force to get the ID of payment of Credit Card (hard coded code 'CB').
1056  if (empty($paymentTypeId) || $paymentTypeId < 0) {
1057  $paymentTypeId = dol_getIdFromCode($db, 'CB', 'c_paiement', 'code', 'id', 1);
1058  }
1059  }
1060 
1061  // Do action only if $FinalPaymentAmt is set (session variable is cleaned after this page to avoid duplicate actions when page is POST a second time)
1062  if (!empty($FinalPaymentAmt) && $paymentTypeId > 0) {
1063  $db->begin();
1064 
1065  // Creation of paiement line for donation
1066  include_once DOL_DOCUMENT_ROOT.'/don/class/paymentdonation.class.php';
1067  $paiement = new PaymentDonation($db);
1068 
1069  $totalpaid = $FinalPaymentAmt;
1070 
1071  if ($currencyCodeType == $conf->currency) {
1072  $paiement->amounts = array($object->id => $totalpaid); // Array with all payments dispatching with donation
1073  } else {
1074  // PaymentDonation does not support multi currency
1075  $postactionmessages[] = 'Payment donation can\'t be payed with diffent currency than '.$conf->currency;
1076  $ispostactionok = -1;
1077  $error++; // Not yet supported
1078  }
1079 
1080  $paiement->fk_donation = $don->id;
1081  $paiement->datep = $now;
1082  $paiement->paymenttype = $paymentTypeId;
1083  $paiement->num_payment = '';
1084  $paiement->note_public = 'Online payment '.dol_print_date($now, 'standard').' from '.$ipaddress;
1085  $paiement->ext_payment_id = $TRANSACTIONID;
1086  $paiement->ext_payment_site = $service;
1087 
1088  if (!$error) {
1089  $paiement_id = $paiement->create($user, 1);
1090  if ($paiement_id < 0) {
1091  $postactionmessages[] = $paiement->error.' '.join("<br>\n", $paiement->errors);
1092  $ispostactionok = -1;
1093  $error++;
1094  } else {
1095  $postactionmessages[] = 'Payment created';
1096  $ispostactionok = 1;
1097 
1098  if ($totalpaid >= $don->getRemainToPay()) {
1099  $don->setPaid($don->id);
1100  }
1101  }
1102  }
1103 
1104  if (!$error && isModEnabled("banque")) {
1105  $bankaccountid = 0;
1106  if ($paymentmethod == 'paybox') {
1107  $bankaccountid = $conf->global->PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS;
1108  } elseif ($paymentmethod == 'paypal') {
1109  $bankaccountid = $conf->global->PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS;
1110  } elseif ($paymentmethod == 'stripe') {
1111  $bankaccountid = $conf->global->STRIPE_BANK_ACCOUNT_FOR_PAYMENTS;
1112  }
1113 
1114  if ($bankaccountid > 0) {
1115  $result = $paiement->addPaymentToBank($user, 'payment_donation', '(DonationPayment)', $bankaccountid, '', '');
1116  if ($result < 0) {
1117  $postactionmessages[] = $paiement->error.' '.join("<br>\n", $paiement->errors);
1118  $ispostactionok = -1;
1119  $error++;
1120  } else {
1121  $postactionmessages[] = 'Bank transaction of payment created';
1122  $ispostactionok = 1;
1123  }
1124  } else {
1125  $postactionmessages[] = 'Setup of bank account to use in module '.$paymentmethod.' was not set. Your payment was really executed but we failed to record it. Please contact us.';
1126  $ispostactionok = -1;
1127  $error++;
1128  }
1129  }
1130 
1131  if (!$error) {
1132  $db->commit();
1133  } else {
1134  $db->rollback();
1135  }
1136  } else {
1137  $postactionmessages[] = 'Failed to get a valid value for "amount paid" ('.$FinalPaymentAmt.') or "payment type id" ('.$paymentTypeId.') to record the payment of donation '.$tmptag['DON'].'. May be payment was already recorded.';
1138  $ispostactionok = -1;
1139  }
1140  } else {
1141  $postactionmessages[] = 'Donation paid '.$tmptag['DON'].' was not found';
1142  $ispostactionok = -1;
1143  }
1144 
1145  // TODO send email with acknowledgment for the donation
1146  // (we need first that the donation module is able to generate a pdf document for the cerfa with pre filled content)
1147  } elseif (array_key_exists('ATT', $tmptag) && $tmptag['ATT'] > 0) {
1148  // Record payment for registration to an event for an attendee
1149  include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
1150  $object = new Facture($db);
1151  $result = $object->fetch($ref);
1152  if ($result) {
1153  $paymentTypeId = 0;
1154  if ($paymentmethod == 'paybox') {
1155  $paymentTypeId = $conf->global->PAYBOX_PAYMENT_MODE_FOR_PAYMENTS;
1156  }
1157  if ($paymentmethod == 'paypal') {
1158  $paymentTypeId = $conf->global->PAYPAL_PAYMENT_MODE_FOR_PAYMENTS;
1159  }
1160  if ($paymentmethod == 'stripe') {
1161  $paymentTypeId = $conf->global->STRIPE_PAYMENT_MODE_FOR_PAYMENTS;
1162  }
1163  if (empty($paymentTypeId)) {
1164  dol_syslog("paymentType = ".$paymentType, LOG_DEBUG, 0, '_payment');
1165 
1166  if (empty($paymentType)) {
1167  $paymentType = 'CB';
1168  }
1169  // May return nothing when paymentType means nothing
1170  // (for example when paymentType is 'Mark', 'Sole', 'Sale', for paypal)
1171  $paymentTypeId = dol_getIdFromCode($db, $paymentType, 'c_paiement', 'code', 'id', 1);
1172 
1173  // If previous line has returned nothing, we force to get the ID of payment of Credit Card (hard coded code 'CB').
1174  if (empty($paymentTypeId) || $paymentTypeId < 0) {
1175  $paymentTypeId = dol_getIdFromCode($db, 'CB', 'c_paiement', 'code', 'id', 1);
1176  }
1177  }
1178 
1179  // Do action only if $FinalPaymentAmt is set (session variable is cleaned after this page to avoid duplicate actions when page is POST a second time)
1180  if (!empty($FinalPaymentAmt) && $paymentTypeId > 0) {
1181  $resultvalidate = $object->validate($user);
1182  if ($resultvalidate < 0) {
1183  $postactionmessages[] = 'Cannot validate invoice';
1184  $ispostactionok = -1;
1185  $error++; // Not yet supported
1186  } else {
1187  $db->begin();
1188 
1189  // Creation of payment line
1190  include_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
1191  $paiement = new Paiement($db);
1192  $paiement->datepaye = $now;
1193  if ($currencyCodeType == $conf->currency) {
1194  $paiement->amounts = array($object->id => $FinalPaymentAmt); // Array with all payments dispatching with invoice id
1195  } else {
1196  $paiement->multicurrency_amounts = array($object->id => $FinalPaymentAmt); // Array with all payments dispatching
1197 
1198  $postactionmessages[] = 'Payment was done in a different currency that currency expected of company';
1199  $ispostactionok = -1;
1200  $error++; // Not yet supported
1201  }
1202  $paiement->paiementid = $paymentTypeId;
1203  $paiement->num_payment = '';
1204  $paiement->note_public = 'Online payment '.dol_print_date($now, 'standard').' from '.$ipaddress.' for event registration';
1205  $paiement->ext_payment_id = $TRANSACTIONID;
1206  $paiement->ext_payment_site = $service;
1207 
1208  if (!$error) {
1209  $paiement_id = $paiement->create($user, 1); // This include closing invoices and regenerating documents
1210  if ($paiement_id < 0) {
1211  $postactionmessages[] = $paiement->error.' '.join("<br>\n", $paiement->errors);
1212  $ispostactionok = -1;
1213  $error++;
1214  } else {
1215  $postactionmessages[] = 'Payment created';
1216  $ispostactionok = 1;
1217  }
1218  }
1219 
1220  if (!$error && isModEnabled("banque")) {
1221  $bankaccountid = 0;
1222  if ($paymentmethod == 'paybox') {
1223  $bankaccountid = $conf->global->PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS;
1224  } elseif ($paymentmethod == 'paypal') {
1225  $bankaccountid = $conf->global->PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS;
1226  } elseif ($paymentmethod == 'stripe') {
1227  $bankaccountid = $conf->global->STRIPE_BANK_ACCOUNT_FOR_PAYMENTS;
1228  }
1229 
1230  if ($bankaccountid > 0) {
1231  $label = '(CustomerInvoicePayment)';
1232  if ($object->type == Facture::TYPE_CREDIT_NOTE) {
1233  $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
1234  }
1235  $result = $paiement->addPaymentToBank($user, 'payment', $label, $bankaccountid, '', '');
1236  if ($result < 0) {
1237  $postactionmessages[] = $paiement->error.' '.join("<br>\n", $paiement->errors);
1238  $ispostactionok = -1;
1239  $error++;
1240  } else {
1241  $postactionmessages[] = 'Bank transaction of payment created';
1242  $ispostactionok = 1;
1243  }
1244  } else {
1245  $postactionmessages[] = 'Setup of bank account to use in module '.$paymentmethod.' was not set. Your payment was really executed but we failed to record it. Please contact us.';
1246  $ispostactionok = -1;
1247  $error++;
1248  }
1249  }
1250 
1251  if (!$error) {
1252  // Validating the attendee
1253  $attendeetovalidate = new ConferenceOrBoothAttendee($db);
1254  $resultattendee = $attendeetovalidate->fetch((int) $tmptag['ATT']);
1255  if ($resultattendee < 0) {
1256  $error++;
1257  setEventMessages(null, $attendeetovalidate->errors, "errors");
1258  } else {
1259  $attendeetovalidate->validate($user);
1260 
1261  $attendeetovalidate->amount = $FinalPaymentAmt;
1262  $attendeetovalidate->date_subscription = dol_now();
1263  $attendeetovalidate->update($user);
1264  }
1265  }
1266 
1267  if (!$error) {
1268  $db->commit();
1269  } else {
1270  setEventMessages(null, $postactionmessages, 'warnings');
1271 
1272  $db->rollback();
1273  }
1274 
1275  if (! $error) {
1276  // Sending mail
1277  $thirdparty = new Societe($db);
1278  $resultthirdparty = $thirdparty->fetch($attendeetovalidate->fk_soc);
1279  if ($resultthirdparty < 0) {
1280  setEventMessages($resultthirdparty->error, $resultthirdparty->errors, "errors");
1281  } else {
1282  require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
1283  include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
1284  $formmail = new FormMail($db);
1285  // Set output language
1286  $outputlangs = new Translate('', $conf);
1287  $outputlangs->setDefaultLang(empty($thirdparty->default_lang) ? $mysoc->default_lang : $thirdparty->default_lang);
1288  // Load traductions files required by page
1289  $outputlangs->loadLangs(array("main", "members", "eventorganization"));
1290  // Get email content from template
1291  $arraydefaultmessage = null;
1292 
1293  $idoftemplatetouse = $conf->global->EVENTORGANIZATION_TEMPLATE_EMAIL_AFT_SUBS_EVENT; // Email to send for Event organization registration
1294 
1295  if (!empty($idoftemplatetouse)) {
1296  $arraydefaultmessage = $formmail->getEMailTemplate($db, 'conferenceorbooth', $user, $outputlangs, $idoftemplatetouse, 1, '');
1297  }
1298 
1299  if (!empty($idoftemplatetouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) {
1300  $subject = $arraydefaultmessage->topic;
1301  $msg = $arraydefaultmessage->content;
1302  } else {
1303  $subject = '['.$appli.'] '.$object->ref.' - '.$outputlangs->trans("NewRegistration").']';
1304  $msg = $outputlangs->trans("OrganizationEventPaymentOfRegistrationWasReceived");
1305  }
1306 
1307  $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $thirdparty);
1308  complete_substitutions_array($substitutionarray, $outputlangs, $object);
1309 
1310  $subjecttosend = make_substitutions($subject, $substitutionarray, $outputlangs);
1311  $texttosend = make_substitutions($msg, $substitutionarray, $outputlangs);
1312 
1313  $sendto = $attendeetovalidate->email;
1314  $cc = '';
1315  if ($thirdparty->email) {
1316  $cc = $thirdparty->email;
1317  }
1318  if ($attendeetovalidate->email_company && $attendeetovalidate->email_company != $thirdparty->email) {
1319  $cc = ($cc ? ', ' : '').$attendeetovalidate->email_company;
1320  }
1321 
1322  $from = !empty($conf->global->MAILING_EMAIL_FROM) ? $conf->global->MAILING_EMAIL_FROM : getDolGlobalString("MAIN_MAIL_EMAIL_FROM");
1323 
1324  $urlback = $_SERVER["REQUEST_URI"];
1325 
1326  $ishtml = dol_textishtml($texttosend); // May contain urls
1327 
1328  // Attach a file ?
1329  $file = '';
1330  $listofpaths = array();
1331  $listofnames = array();
1332  $listofmimes = array();
1333  if (is_object($object)) {
1334  $invoicediroutput = $conf->facture->dir_output;
1335  $fileparams = dol_most_recent_file($invoicediroutput.'/'.$object->ref, preg_quote($object->ref, '/').'[^\-]+');
1336  $file = $fileparams['fullname'];
1337 
1338  $listofpaths = array($file);
1339  $listofnames = array(basename($file));
1340  $listofmimes = array(dol_mimetype($file));
1341  }
1342 
1343  $mailfile = new CMailFile($subjecttosend, $sendto, $from, $texttosend, $listofpaths, $listofmimes, $listofnames, $cc, '', 0, $ishtml);
1344 
1345  $result = $mailfile->sendfile();
1346  if ($result) {
1347  dol_syslog("EMail sent to ".$sendto, LOG_DEBUG, 0, '_payment');
1348  } else {
1349  dol_syslog("Failed to send EMail to ".$sendto.' - '.$mailfile->error, LOG_ERR, 0, '_payment');
1350  }
1351  }
1352  }
1353  }
1354  } else {
1355  $postactionmessages[] = 'Failed to get a valid value for "amount paid" ('.$FinalPaymentAmt.') or "payment type id" ('.$paymentTypeId.') to record the payment of invoice '.$tmptag['ATT'].'. May be payment was already recorded.';
1356  $ispostactionok = -1;
1357  }
1358  } else {
1359  $postactionmessages[] = 'Invoice paid '.$tmptag['ATT'].' was not found';
1360  $ispostactionok = -1;
1361  }
1362  } elseif (array_key_exists('BOO', $tmptag) && $tmptag['BOO'] > 0) {
1363  // Record payment for booth or conference
1364  include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
1365  $object = new Facture($db);
1366  $result = $object->fetch($ref);
1367  if ($result) {
1368  $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"];
1369 
1370  $paymentTypeId = 0;
1371  if ($paymentmethod == 'paybox') {
1372  $paymentTypeId = $conf->global->PAYBOX_PAYMENT_MODE_FOR_PAYMENTS;
1373  }
1374  if ($paymentmethod == 'paypal') {
1375  $paymentTypeId = $conf->global->PAYPAL_PAYMENT_MODE_FOR_PAYMENTS;
1376  }
1377  if ($paymentmethod == 'stripe') {
1378  $paymentTypeId = $conf->global->STRIPE_PAYMENT_MODE_FOR_PAYMENTS;
1379  }
1380  if (empty($paymentTypeId)) {
1381  dol_syslog("paymentType = ".$paymentType, LOG_DEBUG, 0, '_payment');
1382 
1383  if (empty($paymentType)) {
1384  $paymentType = 'CB';
1385  }
1386  // May return nothing when paymentType means nothing
1387  // (for example when paymentType is 'Mark', 'Sole', 'Sale', for paypal)
1388  $paymentTypeId = dol_getIdFromCode($db, $paymentType, 'c_paiement', 'code', 'id', 1);
1389 
1390  // If previous line has returned nothing, we force to get the ID of payment of Credit Card (hard coded code 'CB').
1391  if (empty($paymentTypeId) || $paymentTypeId < 0) {
1392  $paymentTypeId = dol_getIdFromCode($db, 'CB', 'c_paiement', 'code', 'id', 1);
1393  }
1394  }
1395 
1396  // Do action only if $FinalPaymentAmt is set (session variable is cleaned after this page to avoid duplicate actions when page is POST a second time)
1397  if (!empty($FinalPaymentAmt) && $paymentTypeId > 0) {
1398  $resultvalidate = $object->validate($user);
1399  if ($resultvalidate < 0) {
1400  $postactionmessages[] = 'Cannot validate invoice';
1401  $ispostactionok = -1;
1402  $error++; // Not yet supported
1403  } else {
1404  $db->begin();
1405 
1406  // Creation of payment line
1407  include_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
1408  $paiement = new Paiement($db);
1409  $paiement->datepaye = $now;
1410  if ($currencyCodeType == $conf->currency) {
1411  $paiement->amounts = array($object->id => $FinalPaymentAmt); // Array with all payments dispatching with invoice id
1412  } else {
1413  $paiement->multicurrency_amounts = array($object->id => $FinalPaymentAmt); // Array with all payments dispatching
1414 
1415  $postactionmessages[] = 'Payment was done in a different currency that currency expected of company';
1416  $ispostactionok = -1;
1417  $error++; // Not yet supported
1418  }
1419  $paiement->paiementid = $paymentTypeId;
1420  $paiement->num_payment = '';
1421  $paiement->note_public = 'Online payment '.dol_print_date($now, 'standard').' from '.$ipaddress;
1422  $paiement->ext_payment_id = $TRANSACTIONID;
1423  $paiement->ext_payment_site = $service;
1424 
1425  if (!$error) {
1426  $paiement_id = $paiement->create($user, 1); // This include closing invoices and regenerating documents
1427  if ($paiement_id < 0) {
1428  $postactionmessages[] = $paiement->error.' '.join("<br>\n", $paiement->errors);
1429  $ispostactionok = -1;
1430  $error++;
1431  } else {
1432  $postactionmessages[] = 'Payment created';
1433  $ispostactionok = 1;
1434  }
1435  }
1436 
1437  if (!$error && isModEnabled("banque")) {
1438  $bankaccountid = 0;
1439  if ($paymentmethod == 'paybox') {
1440  $bankaccountid = $conf->global->PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS;
1441  } elseif ($paymentmethod == 'paypal') {
1442  $bankaccountid = $conf->global->PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS;
1443  } elseif ($paymentmethod == 'stripe') {
1444  $bankaccountid = $conf->global->STRIPE_BANK_ACCOUNT_FOR_PAYMENTS;
1445  }
1446 
1447  if ($bankaccountid > 0) {
1448  $label = '(CustomerInvoicePayment)';
1449  if ($object->type == Facture::TYPE_CREDIT_NOTE) {
1450  $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
1451  }
1452  $result = $paiement->addPaymentToBank($user, 'payment', $label, $bankaccountid, '', '');
1453  if ($result < 0) {
1454  $postactionmessages[] = $paiement->error.' '.join("<br>\n", $paiement->errors);
1455  $ispostactionok = -1;
1456  $error++;
1457  } else {
1458  $postactionmessages[] = 'Bank transaction of payment created';
1459  $ispostactionok = 1;
1460  }
1461  } else {
1462  $postactionmessages[] = 'Setup of bank account to use in module '.$paymentmethod.' was not set. Your payment was really executed but we failed to record it. Please contact us.';
1463  $ispostactionok = -1;
1464  $error++;
1465  }
1466  }
1467 
1468  if (!$error) {
1469  // Putting the booth to "suggested" state
1470  $booth = new ConferenceOrBooth($db);
1471  $resultbooth = $booth->fetch((int) $tmptag['BOO']);
1472  if ($resultbooth < 0) {
1473  $error++;
1474  setEventMessages(null, $booth->errors, "errors");
1475  } else {
1476  $booth->status = CONFERENCEORBOOTH::STATUS_SUGGESTED;
1477  $resultboothupdate = $booth->update($user);
1478  if ($resultboothupdate<0) {
1479  // Finding the thirdparty by getting the invoice
1480  $invoice = new Facture($db);
1481  $resultinvoice = $invoice->fetch($ref);
1482  if ($resultinvoice<0) {
1483  $postactionmessages[] = 'Could not find the associated invoice.';
1484  $ispostactionok = -1;
1485  $error++;
1486  } else {
1487  $thirdparty = new Societe($db);
1488  $resultthirdparty = $thirdparty->fetch($invoice->socid);
1489  if ($resultthirdparty<0) {
1490  $error++;
1491  setEventMessages(null, $thirdparty->errors, "errors");
1492  } else {
1493  // Sending mail
1494  require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
1495  include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
1496  $formmail = new FormMail($db);
1497  // Set output language
1498  $outputlangs = new Translate('', $conf);
1499  $outputlangs->setDefaultLang(empty($thirdparty->default_lang) ? $mysoc->default_lang : $thirdparty->default_lang);
1500  // Load traductions files required by page
1501  $outputlangs->loadLangs(array("main", "members", "eventorganization"));
1502  // Get email content from template
1503  $arraydefaultmessage = null;
1504 
1505  $idoftemplatetouse = $conf->global->EVENTORGANIZATION_TEMPLATE_EMAIL_AFT_SUBS_BOOTH; // Email sent after registration for a Booth
1506 
1507  if (!empty($idoftemplatetouse)) {
1508  $arraydefaultmessage = $formmail->getEMailTemplate($db, 'conferenceorbooth', $user, $outputlangs, $idoftemplatetouse, 1, '');
1509  }
1510 
1511  if (!empty($idoftemplatetouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) {
1512  $subject = $arraydefaultmessage->topic;
1513  $msg = $arraydefaultmessage->content;
1514  } else {
1515  $subject = '['.$appli.'] '.$booth->ref.' - '.$outputlangs->trans("NewRegistration").']';
1516  $msg = $outputlangs->trans("OrganizationEventPaymentOfBoothWasReceived");
1517  }
1518 
1519  $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $thirdparty);
1520  complete_substitutions_array($substitutionarray, $outputlangs, $object);
1521 
1522  $subjecttosend = make_substitutions($subject, $substitutionarray, $outputlangs);
1523  $texttosend = make_substitutions($msg, $substitutionarray, $outputlangs);
1524 
1525  $sendto = $thirdparty->email;
1526  $from = $conf->global->MAILING_EMAIL_FROM;
1527  $urlback = $_SERVER["REQUEST_URI"];
1528 
1529  $ishtml = dol_textishtml($texttosend); // May contain urls
1530 
1531  $mailfile = new CMailFile($subjecttosend, $sendto, $from, $texttosend, array(), array(), array(), '', '', 0, $ishtml);
1532 
1533  $result = $mailfile->sendfile();
1534  if ($result) {
1535  dol_syslog("EMail sent to ".$sendto, LOG_DEBUG, 0, '_payment');
1536  } else {
1537  dol_syslog("Failed to send EMail to ".$sendto, LOG_ERR, 0, '_payment');
1538  }
1539  }
1540  }
1541  }
1542  }
1543  }
1544 
1545  if (!$error) {
1546  $db->commit();
1547  } else {
1548  $db->rollback();
1549  }
1550  }
1551  } else {
1552  $postactionmessages[] = 'Failed to get a valid value for "amount paid" ('.$FinalPaymentAmt.') or "payment type id" ('.$paymentTypeId.') to record the payment of invoice '.$tmptag['ATT'].'. May be payment was already recorded.';
1553  $ispostactionok = -1;
1554  }
1555  } else {
1556  $postactionmessages[] = 'Invoice paid '.$tmptag['ATT'].' was not found';
1557  $ispostactionok = -1;
1558  }
1559  } else {
1560  // Nothing done
1561  }
1562 }
1563 
1564 
1565 // Set $appli for emails title
1566 $appli = $mysoc->name;
1567 
1568 
1569 if ($ispaymentok) {
1570  // Get on url call
1571  $onlinetoken = empty($PAYPALTOKEN) ? $_SESSION['onlinetoken'] : $PAYPALTOKEN;
1572  $payerID = empty($PAYPALPAYERID) ? $_SESSION['payerID'] : $PAYPALPAYERID;
1573  // Set by newpayment.php
1574  $currencyCodeType = $_SESSION['currencyCodeType'];
1575  $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"];
1576  $paymentType = $_SESSION['PaymentType']; // Seems used by paypal only
1577 
1578  if (is_object($object) && method_exists($object, 'call_trigger')) {
1579  // Call trigger
1580  $result = $object->call_trigger('PAYMENTONLINE_PAYMENT_OK', $user);
1581  if ($result < 0) {
1582  $error++;
1583  }
1584  // End call triggers
1585  } elseif (get_class($object) == 'stdClass') {
1586  //In some case $object is not instanciate (for paiement on custom object) We need to deal with payment
1587  include_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
1588  $paiement = new Paiement($db);
1589  $result = $paiement->call_trigger('PAYMENTONLINE_PAYMENT_OK', $user);
1590  if ($result < 0) $error++;
1591  }
1592 
1593  print $langs->trans("YourPaymentHasBeenRecorded")."<br>\n";
1594  if ($TRANSACTIONID) {
1595  print $langs->trans("ThisIsTransactionId", $TRANSACTIONID)."<br><br>\n";
1596  }
1597 
1598  $key = 'ONLINE_PAYMENT_MESSAGE_OK';
1599  if (!empty($conf->global->$key)) {
1600  print '<br>';
1601  print $conf->global->$key;
1602  }
1603 
1604  $sendemail = '';
1605  if (!empty($conf->global->ONLINE_PAYMENT_SENDEMAIL)) {
1606  $sendemail = $conf->global->ONLINE_PAYMENT_SENDEMAIL;
1607  }
1608 
1609  $tmptag = dolExplodeIntoArray($fulltag, '.', '=');
1610 
1611  dol_syslog("Send email to admins if we have to (sendemail = ".$sendemail.")", LOG_DEBUG, 0, '_payment');
1612 
1613  // Send an email to admins
1614  if ($sendemail) {
1615  $companylangs = new Translate('', $conf);
1616  $companylangs->setDefaultLang($mysoc->default_lang);
1617  $companylangs->loadLangs(array('main', 'members', 'bills', 'paypal', 'paybox'));
1618 
1619  $sendto = $sendemail;
1620  $from = !empty($conf->global->MAILING_EMAIL_FROM) ? $conf->global->MAILING_EMAIL_FROM : getDolGlobalString("MAIN_MAIL_EMAIL_FROM");
1621  // Define $urlwithroot
1622  $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
1623  $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
1624  //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
1625 
1626  // Define link to login card
1627 
1628  $urlback = $_SERVER["REQUEST_URI"];
1629  $topic = '['.$appli.'] '.$companylangs->transnoentitiesnoconv("NewOnlinePaymentReceived");
1630  $content = "";
1631  if (array_key_exists('MEM', $tmptag)) {
1632  $url = $urlwithroot."/adherents/subscription.php?rowid=".((int) $tmptag['MEM']);
1633  $content .= '<strong>'.$companylangs->trans("PaymentSubscription")."</strong><br><br>\n";
1634  $content .= $companylangs->trans("MemberId").': <strong>'.$tmptag['MEM']."</strong><br>\n";
1635  $content .= $companylangs->trans("Link").': <a href="'.$url.'">'.$url.'</a>'."<br>\n";
1636  } elseif (array_key_exists('INV', $tmptag)) {
1637  $url = $urlwithroot."/compta/facture/card.php?id=".((int) $tmptag['INV']);
1638  $content .= '<strong>'.$companylangs->trans("Payment")."</strong><br><br>\n";
1639  $content .= $companylangs->trans("InvoiceId").': <strong>'.$tmptag['INV']."</strong><br>\n";
1640  //$content.=$companylangs->trans("ThirdPartyId").': '.$tmptag['CUS']."<br>\n";
1641  $content .= $companylangs->trans("Link").': <a href="'.$url.'">'.$url.'</a>'."<br>\n";
1642  } else {
1643  $content .= $companylangs->transnoentitiesnoconv("NewOnlinePaymentReceived")."<br>\n";
1644  }
1645  $content .= $companylangs->transnoentities("PostActionAfterPayment").' : ';
1646  if ($ispostactionok > 0) {
1647  //$topic.=' ('.$companylangs->transnoentitiesnoconv("Status").' '.$companylangs->transnoentitiesnoconv("OK").')';
1648  $content .= '<span style="color: green">'.$companylangs->transnoentitiesnoconv("OK").'</span>';
1649  } elseif ($ispostactionok == 0) {
1650  $content .= $companylangs->transnoentitiesnoconv("None");
1651  } else {
1652  $topic .= ($ispostactionok ? '' : ' ('.$companylangs->trans("WarningPostActionErrorAfterPayment").')');
1653  $content .= '<span style="color: red">'.$companylangs->transnoentitiesnoconv("Error").'</span>';
1654  }
1655  $content .= '<br>'."\n";
1656  foreach ($postactionmessages as $postactionmessage) {
1657  $content .= ' * '.$postactionmessage.'<br>'."\n";
1658  }
1659  if ($ispostactionok < 0) {
1660  $content .= $langs->transnoentities("ARollbackWasPerformedOnPostActions");
1661  }
1662  $content .= '<br>'."\n";
1663 
1664  $content .= "<br>\n";
1665  $content .= '<u>'.$companylangs->transnoentitiesnoconv("TechnicalInformation").":</u><br>\n";
1666  $content .= $companylangs->transnoentitiesnoconv("OnlinePaymentSystem").': <strong>'.$paymentmethod."</strong><br>\n";
1667  $content .= $companylangs->transnoentitiesnoconv("ThisIsTransactionId").': <strong>'.$TRANSACTIONID."</strong><br>\n";
1668  $content .= $companylangs->transnoentitiesnoconv("ReturnURLAfterPayment").': '.$urlback."<br>\n";
1669  $content .= "<br>\n";
1670  $content .= "tag=".$fulltag."<br>\ntoken=".$onlinetoken."<br>\npaymentType=".$paymentType."<br>\ncurrencycodeType=".$currencyCodeType."<br>\npayerId=".$payerID."<br>\nipaddress=".$ipaddress."<br>\nFinalPaymentAmt=".$FinalPaymentAmt."<br>\n";
1671 
1672  if (!empty($ErrorCode)) {
1673  $content .= "ErrorCode = ".$ErrorCode."<br>\n";
1674  }
1675  if (!empty($ErrorShortMsg)) {
1676  $content .= "ErrorShortMsg = ".$ErrorShortMsg."<br>\n";
1677  }
1678  if (!empty($ErrorLongMsg)) {
1679  $content .= "ErrorLongMsg = ".$ErrorLongMsg."<br>\n";
1680  }
1681  if (!empty($ErrorSeverityCode)) {
1682  $content .= "ErrorSeverityCode = ".$ErrorSeverityCode."<br>\n";
1683  }
1684 
1685 
1686  $ishtml = dol_textishtml($content); // May contain urls
1687 
1688  require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
1689  $mailfile = new CMailFile($topic, $sendto, $from, $content, array(), array(), array(), '', '', 0, $ishtml);
1690 
1691  $result = $mailfile->sendfile();
1692  if ($result) {
1693  dol_syslog("EMail sent to ".$sendto, LOG_DEBUG, 0, '_payment');
1694  //dol_syslog("EMail sent to ".$sendto, LOG_DEBUG, 0);
1695  } else {
1696  dol_syslog("Failed to send EMail to ".$sendto, LOG_ERR, 0, '_payment');
1697  //dol_syslog("Failed to send EMail to ".$sendto, LOG_ERR, 0);
1698  }
1699  }
1700 } else {
1701  // Get on url call
1702  $onlinetoken = empty($PAYPALTOKEN) ? $_SESSION['onlinetoken'] : $PAYPALTOKEN;
1703  $payerID = empty($PAYPALPAYERID) ? $_SESSION['payerID'] : $PAYPALPAYERID;
1704  // Set by newpayment.php
1705  $paymentType = $_SESSION['PaymentType'];
1706  $currencyCodeType = $_SESSION['currencyCodeType'];
1707  $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"];
1708 
1709  if (is_object($object) && method_exists($object, 'call_trigger')) {
1710  // Call trigger
1711  $result = $object->call_trigger('PAYMENTONLINE_PAYMENT_KO', $user);
1712  if ($result < 0) {
1713  $error++;
1714  }
1715  // End call triggers
1716  }
1717 
1718  print $langs->trans('DoExpressCheckoutPaymentAPICallFailed')."<br>\n";
1719  print $langs->trans('DetailedErrorMessage').": ".$ErrorLongMsg."<br>\n";
1720  print $langs->trans('ShortErrorMessage').": ".$ErrorShortMsg."<br>\n";
1721  print $langs->trans('ErrorCode').": ".$ErrorCode."<br>\n";
1722  print $langs->trans('ErrorSeverityCode').": ".$ErrorSeverityCode."<br>\n";
1723 
1724  if ($mysoc->email) {
1725  print "\nPlease, send a screenshot of this page to ".$mysoc->email."<br>\n";
1726  }
1727 
1728  $sendemail = '';
1729  if (!empty($conf->global->PAYMENTONLINE_SENDEMAIL)) {
1730  $sendemail = $conf->global->PAYMENTONLINE_SENDEMAIL;
1731  }
1732  // TODO Remove local option to keep only the generic one ?
1733  if ($paymentmethod == 'paypal' && !empty($conf->global->PAYPAL_PAYONLINE_SENDEMAIL)) {
1734  $sendemail = $conf->global->PAYPAL_PAYONLINE_SENDEMAIL;
1735  } elseif ($paymentmethod == 'paybox' && !empty($conf->global->PAYBOX_PAYONLINE_SENDEMAIL)) {
1736  $sendemail = $conf->global->PAYBOX_PAYONLINE_SENDEMAIL;
1737  } elseif ($paymentmethod == 'stripe' && !empty($conf->global->STRIPE_PAYONLINE_SENDEMAIL)) {
1738  $sendemail = $conf->global->STRIPE_PAYONLINE_SENDEMAIL;
1739  }
1740 
1741  // Send warning of error to administrator
1742  if ($sendemail) {
1743  $companylangs = new Translate('', $conf);
1744  $companylangs->setDefaultLang($mysoc->default_lang);
1745  $companylangs->loadLangs(array('main', 'members', 'bills', 'paypal', 'paybox'));
1746 
1747  $sendto = $sendemail;
1748  $from = !empty($conf->global->MAILING_EMAIL_FROM) ? $conf->global->MAILING_EMAIL_FROM : getDolGlobalString("MAIN_MAIL_EMAIL_FROM");
1749  // Define $urlwithroot
1750  $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
1751  $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
1752  //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
1753 
1754  $urlback = $_SERVER["REQUEST_URI"];
1755  $topic = '['.$appli.'] '.$companylangs->transnoentitiesnoconv("ValidationOfPaymentFailed");
1756  $content = "";
1757  $content .= '<span style="color: orange">'.$companylangs->transnoentitiesnoconv("PaymentSystemConfirmPaymentPageWasCalledButFailed")."</span>\n";
1758 
1759  $content .= "<br><br>\n";
1760  $content .= '<u>'.$companylangs->transnoentitiesnoconv("TechnicalInformation").":</u><br>\n";
1761  $content .= $companylangs->transnoentitiesnoconv("OnlinePaymentSystem").': <strong>'.$paymentmethod."</strong><br>\n";
1762  $content .= $companylangs->transnoentitiesnoconv("ReturnURLAfterPayment").': '.$urlback."<br>\n";
1763  $content .= "<br>\n";
1764  $content .= "tag=".$fulltag."<br>\ntoken=".$onlinetoken."<br>\npaymentType=".$paymentType."<br>\ncurrencycodeType=".$currencyCodeType."<br>\npayerId=".$payerID."<br>\nipaddress=".$ipaddress."<br>\nFinalPaymentAmt=".$FinalPaymentAmt."<br>\n";
1765 
1766 
1767  $ishtml = dol_textishtml($content); // May contain urls
1768 
1769  require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
1770  $mailfile = new CMailFile($topic, $sendto, $from, $content, array(), array(), array(), '', '', 0, $ishtml);
1771 
1772  $result = $mailfile->sendfile();
1773  if ($result) {
1774  dol_syslog("EMail sent to ".$sendto, LOG_DEBUG, 0, '_payment');
1775  } else {
1776  dol_syslog("Failed to send EMail to ".$sendto, LOG_ERR, 0, '_payment');
1777  }
1778  }
1779 }
1780 
1781 
1782 print "\n</div>\n";
1783 
1784 print "<!-- Info for payment: FinalPaymentAmt=".dol_escape_htmltag($FinalPaymentAmt)." paymentTypeId=".dol_escape_htmltag($paymentTypeId)." currencyCodeType=".dol_escape_htmltag($currencyCodeType)." -->\n";
1785 
1786 
1787 htmlPrintOnlinePaymentFooter($mysoc, $langs, 0, $suffix);
1788 
1789 
1790 // Clean session variables to avoid duplicate actions if post is resent
1791 unset($_SESSION["FinalPaymentAmt"]);
1792 unset($_SESSION["TRANSACTIONID"]);
1793 
1794 
1795 llxFooter('', 'public');
1796 
1797 $db->close();
if(!defined('NOREQUIRESOC')) if(!defined('NOREQUIRETRAN')) if(!defined('NOTOKENRENEWAL')) if(!defined('NOREQUIREMENU')) if(!defined('NOREQUIREHTML')) if(!defined('NOREQUIREAJAX')) llxHeader()
Empty header.
Definition: wrapper.php:56
llxFooter()
Empty footer.
Definition: wrapper.php:70
Class to manage members of a foundation.
Class to manage members type.
Class to send emails (with attachments or not) Usage: $mailfile = new CMailFile($subject,...
Class to manage customers orders.
Class for ConferenceOrBoothAttendee.
Class for ConferenceOrBooth.
Class to manage donations.
Definition: don.class.php:39
Class to manage invoices.
const TYPE_CREDIT_NOTE
Credit note invoice.
Classe permettant la generation du formulaire html d'envoi de mail unitaire Usage: $formail = new For...
Class to manage payments of customer invoices.
Class to manage payments of donations.
Class to manage third parties objects (customers, suppliers, prospects...)
Stripe class.
Class to manage translations.
Class to manage Dolibarr users.
Definition: user.class.php:47
if(isModEnabled('facture') &&!empty($user->rights->facture->lire)) if((isModEnabled('fournisseur') &&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) && $user->hasRight("fournisseur", "facture", "lire"))||(isModEnabled('supplier_invoice') && $user->hasRight("supplier_invoice", "lire"))) if(isModEnabled('don') &&!empty($user->rights->don->lire)) if(isModEnabled('tax') &&!empty($user->rights->tax->charges->lire)) if(isModEnabled('facture') &&isModEnabled('commande') && $user->hasRight("commande", "lire") &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) $resql
Social contributions to pay.
Definition: index.php:745
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0)
Add a delay to a date.
Definition: date.lib.php:121
dol_most_recent_file($dir, $regexfilter='', $excludefilter=array('(\.meta|_preview.*\.png)$', '^\.'), $nohook=false, $mode='')
Return file(s) into a directory (by default most recent)
Definition: files.lib.php:2429
dolExplodeIntoArray($string, $delimiter=';', $kv='=')
Split a string with 2 keys into key array.
dol_mimetype($file, $default='application/octet-stream', $mode=0)
Return MIME type of a file from its name with extension.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0)
Returns text escaped for inclusion in HTML alt or title tags, or into values of HTML input fields.
dol_print_error($db='', $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='')
Set event messages in dol_events session object.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs='', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
dol_now($mode='auto')
Return date for now.
dol_getIdFromCode($db, $key, $tablename, $fieldkey='code', $fieldid='id', $entityfilter=0, $filters='')
Return an id or code from a code or id.
dol_clone($object, $native=0)
Create a clone of instance of object (new instance with same value for each properties) With native =...
dol_concatdesc($text1, $text2, $forxml=false, $invert=false)
Concat 2 descriptions with a new line between them (second operand after first one with appropriate n...
complete_substitutions_array(&$substitutionarray, $outputlangs, $object=null, $parameters=null, $callfunc="completesubstitutionarray")
Complete the $substitutionarray with more entries coming from external module that had set the "subst...
make_substitutions($text, $substitutionarray, $outputlangs=null, $converttextinhtmlifnecessary=0)
Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newva...
dol_textishtml($msg, $option=0)
Return if a text is a html content.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
if(!function_exists('utf8_encode')) if(!function_exists('utf8_decode')) getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
getCommonSubstitutionArray($outputlangs, $onlykey=0, $exclude=null, $object=null)
Return array of possible common substitutions.
isModEnabled($module)
Is Dolibarr module enabled.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
if(!defined( 'CSRFCHECK_WITH_TOKEN'))
confirmPayment($token, $paymentType, $currencyCodeType, $payerID, $ipaddress, $FinalPaymentAmt, $tag)
Validate payment.
Definition: paypal.lib.php:357
getDetails($token)
Prepares the parameters for the GetExpressCheckoutDetails API Call.
Definition: paypal.lib.php:308
httponly_accessforbidden($message=1, $http_response_code=403, $stringalreadysanitized=0)
Show a message to say access is forbidden and stop program.