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