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