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